Categories
data structures java selection sort

selection sort

In this post, We will learn about the selection sort algorithm in the java language. It is a comparison-based sorting algorithm

Selection sort will select the element from an array, and keep on compare with the remaining elements.

End of each iteration we will obtain the minimum value, After that we will swap the minimum element to the sorted array

Likewise, it will select all the elements in the array and compare them with the remaining element

Unsorted Input array: [ 12, 4, 6, 7, 2, 5 ]
Sorted Output array:  [ 2, 4, 5, 6, 7, 12 ]

Execution Steps

  1. [2, 4, 6, 7, 12, 5]
  2. [2, 4, 6, 7, 12, 5]
  3. [2, 4, 5, 7, 12, 6]
  4. [2, 4, 5, 6, 12, 7]
  5. [2, 4, 5, 6, 7, 12]

Selection Sort

Time Complexity : O(n^2)

Code

package example;

import java.util.Arrays;

public class SelectionSort {

	private void sortArray(int[] arr) {

		for (int i = 0; i < arr.length; i++) {
			int selectionItem = i;
			for (int j = i + 1; j < arr.length; j++) {
				if (arr[j] < arr[selectionItem]) {
					selectionItem = j;
				}
			}
			int temp = arr[selectionItem];
			arr[selectionItem] = arr[i];
			arr[i] = temp;
		}
	}

	public static void main(String[] args) {
		int[] arr = { 12, 4, 6, 7, 2, 5 };
		SelectionSort selectionSort = new SelectionSort();
		selectionSort.sortArray(arr);
		System.out.println(Arrays.toString(arr));
	}
}

Output

[2, 4, 5, 6, 7, 12]

Related Articles

Categories
Bubble sort data structures java

bubble sort algorithm

In this post, we will learn about the bubble sort algorithm. The bubble sort algorithm is one of the important sorting algorithms

It will compare two adjacent elements in an array and swap the right value to the left if it is lesser than left

Bubble Sort

Time Complexity: O(n^2)
Values1012462
Position01234
Input Array
Step 1
Iterate the given array using for loop
Step 2 
Add one more iteration within the for loop again
Step 3
compare the first element with second element
Step 4 
If first element greater than second element swap the two elements
Step 5 
Compare the second element with third element 
Step 6
If Second element is greater than third element, then swap the two elements 
Step 7 
Continue until nth element 
Step 1
Step2
Step 3
Step 4
Result of the first iteration

Java Implementation


public class BubbleSort {

	private void sortArray(int arr[]) {
		for (int i = 0; i < arr.length; i++) {
			boolean isSwap = false;
			for (int j = 0; j < arr.length - i - 1; j++) {
				if (arr[j] > arr[j + 1]) {
					int temp = arr[j + 1];
					arr[j + 1] = arr[j];
					arr[j] = temp;
					isSwap = true;
				}
			}
			if (!isSwap) {
				break;
			}
		}
	}

	public static void main(String[] args) {
		int arr[] = { 10, 12, 4, 6, 2 };
		System.out.println("Array Before sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}
		BubbleSort bubbleSort = new BubbleSort();
		bubbleSort.sortArray(arr);

		System.out.println("\nArray After Sorting");
		for (int i = 0; i < arr.length; i++) {
			System.out.print(arr[i] + "  ");
		}

	}

}

Output

Array Before sorting
10  12  4  6  2  
Array After Sorting
2  4  6  10  12  
Categories
binary search data structures java

search in rotated sorted array

In this post we will discuss about search in rotated sorted array in efficient way using java

Problem Statement

Input: rotated sorted array
Time Complexity: O(logn)
Efficient Approach: Binary Search

Test Case 1
Input: { 7, 8, 0, 1, 2, 3, 4, 5, 6 }
Target:  8
Output: 1

Test Case 2
Input: { 7, 8, 0, 1, 2, 3, 4, 5, 6 }
Target:  100
Output: -1

Explanation

  • Consider that array doesn’t have duplicates
  • As initial step, we are going to let left pointer =0 & right pointer = array.lenght-1
  • As per binary search we are going to find the mid of the array
  • In case target value matches mid value, then return the mid
  • find the left and right position based on the below solution in iterative way

Solution


public class RotatedBinarySearchExample {

	private int rotatedBinarySearch(int[] nums, int target) {

		// Basic check 
		if (null == nums || nums.length == 0) {
			return -1;
		}
		if (nums.length == 1 && nums[0] == target) {
			return 0;
		}

		int mid = 0;
		int leftPointer = 0;
		int rightPointer = nums.length - 1;

		while (leftPointer <= rightPointer) {

			mid = (leftPointer + rightPointer) / 2;

			if (nums[mid] == target) {
				return mid;
			} else if (nums[leftPointer] <= nums[mid]) { 
				if (target >= nums[leftPointer] && target <= nums[mid]) {
					rightPointer = mid - 1;
				} else {
					leftPointer = mid + 1;
				}

			} else {
				if (target >= nums[mid] && target <= nums[rightPointer]) {
					leftPointer = mid + 1;
				} else {
					rightPointer = mid - 1;
				}
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		RotatedBinarySearchExample rotatedBinarySearchExample = new RotatedBinarySearchExample();
		int[] array = { 7, 8, 0, 1, 2, 3, 4, 5, 6 };
		int targetNumber = 8;
		int output = rotatedBinarySearchExample.rotatedBinarySearch(array, targetNumber);
		System.out.println(output);
	}

}

Output

1

Reference

Categories
binary search data structures java

binary search algorithm

Binary search algorithm is one of the fastest way to identify the element from an sorted array. It is also the commonly asked data structure interview questions.

It works based on divide and conquer mechanism. It will divide the given array into 2 parts and discard the one part. So it will works faster for a big array compared to linear search.

Time complexity of Binary Search is O(logn)

Below is the give array structure

With the above given array we have to find the position of 9, Using linear search we can find easily, But the time complexity will be O(N)

Below is java code snippet to find the position using Binary Search

public class BinarySearchExample {

	private int binarySearch(int[] array, int target) {
		int leftIndex = 0;
		int rightIndex = array.length - 1;
		while (leftIndex <= rightIndex) {
			// find the middle Index
			int middleIndex = (leftIndex + rightIndex) / 2;
			if (array[middleIndex] == target) {
				return middleIndex;
			}
			if (target > array[middleIndex]) {
				// ignoring the left side of array
				leftIndex = middleIndex + 1;
			} else {
				// ignoring the right side of array
				rightIndex = middleIndex - 1;
			}
		}
		return -1;
	}

	public static void main(String[] args) {
		int[] i = { 2, 3, 5, 6, 7, 9,10 };
		int targetNumber = 9;
		BinarySearchExample object = new BinarySearchExample();
		int output = object.binarySearch(i, targetNumber);
		System.out.println(output);
	}

}
Output
5

Categories
Angular

lazy loading in angular

lazy loading in angular is one of the most important concept. You have to understand this while designing an enterprise level angular app

What is lazy loading ?

In single page application we will load all the components and required java script and css files in single shot

But this will take more time when we have more components and more dependencies.

In order to avoid this angular has cool feature which is called lazy loading. which will load required module on need basis

ngModule

ngModule will allow us to group the things together, Module is great way to organize an application

Every angular application will have one base module which is called appModule

@NgModule decorator will make class as module. which will come with declarations,providers,imports. Below is the sample module 

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { LazyRoutingModule } from './lazy-routing.module';
import { LazyComponent } from 'src/app/lazy/lazy/lazy.component';
import { MaterialModule } from '../material/material.module';
import { MatTabsModule } from '@angular/material/tabs';
import {MatCardModule} from '@angular/material/card';
import { SampleComponent } from 'src/app/lazy/sample/sample/sample.component';
import {MatButtonModule} from '@angular/material/button';


@NgModule({
  declarations: [LazyComponent,SampleComponent],
  imports: [
    CommonModule,
    LazyRoutingModule,
    MaterialModule,
  ]
})
export class LazyModule { }

Lazy Loading Steps

  • Create new angular project
    • ng new lazy-example –routing
  • Create new component(HomeComponent)
    • ng new component home
  • Create new Component (LazyComponent)
    • ng new component lazy
  • Create new module(LazyModule)
    • ng new module lazy –routing

Below is the folder structure of our application

We have two components.& two Modules

  • AppModule is the base module used while application launch
  • LazyModule is the lazy module used while user clicks the lazy url
  • HomeComponent will get initialized while application launch via appModule
  • LazyComponent will get initialized while clicking the lazy routing url via LazyModule

Declare the HomeComponent in AppModule as like below

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { AppRoutingModule } from './app-routing.module';
import { HomeComponent } from './components/home/home.component';

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    BrowserAnimationsModule
  ],
  declarations: [AppComponent, HomeComponent],
  bootstrap: [AppComponent]
})
export class AppModule {}

Declare the LazyComponent in LazyModule as like below

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { LazyRoutingModule } from './lazy-routing.module';
import { MatTabsModule } from '@angular/material/tabs';
import { LazyComponent } from '../../components/lazy/lazy.component';

@NgModule({
  imports: [CommonModule, LazyRoutingModule, MatTabsModule],
  declarations: [LazyComponent]
})
export class LazyModule {}

The important point is routing. We have to mention that load children (LazyModule) in app-routing.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule, Routes } from '@angular/router';
import { LazyModule } from './modules/lazy/lazy.module';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'lazy', loadChildren: () => LazyModule }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule],
  declarations: []
})
export class AppRoutingModule {}

As like app-routing we have to mention the home path in lazy-routing.module.ts file as like below

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LazyComponent } from '../../components/lazy/lazy.component';

const routes: Routes = [{ path: '', component: LazyComponent }];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  declarations: []
})
export class LazyRoutingModule {}

That’s it you can see the output as like below

StackBlitz URL:

https://stackblitz.com/edit/angular-ivy-rpqusl?file=src/app/app.component.ts

Related Articles

Categories
ansible devops

ansible playbook example

In this post we will see ansible playbook example, Play book is written in yaml format. Inside that we will have multiple tasks and roles

Below is the simple ansible play book with mutiple task

---
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"	
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"
- hosts: 10.118.225.56
  tasks:
    - name: first server
      shell: "mkdir /home/host1"

Related Articles

when condition in ansible playbook

Categories
ag-grid Angular

ag grid angular examples

In this post, we will see ag grid angular examples. ag grid is one of the most commonly used grid in modern web applications. It is easy to integrate with java script, angular. react ,vue.js.

It is available in both community & enterprise edition
https://www.ag-grid.com/documentation/

In this post we will learn to integrate the ag grid with angular. We are consider that you have a angular project already

Install ag grid in angular project

Run below commands to install ag grid in the angular project, Below will install the ag grid community version to your application

npm install --save ag-grid-community ag-grid-angular
npm install

app.module.ts

Add ag-grid module in app.module.ts as like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([])
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule {}

Ag-grid Styling

ag-grid is coming with multiple styling and themes you have to add below code in the src/style.css file

@import "../node_modules/ag-grid-community/dist/styles/ag-grid.css";
@import "../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css";

Below are the providing themes in ag grid

  • ag-theme-alpine
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-alpine.css”;
  • ag-theme-alpine-dark
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-alpine-dark.css”;
  • ag-theme-balham
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-balham.css”;
  • ag-theme-balham-dark
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-balham-dark.css”
  • ag-theme-material
    • @import “../node_modules/ag-grid-community/dist/styles/ag-theme-material.css”

Adding grid in angular

We have to add column definition and row data in the component.ts file, Below is the snippet of app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ag-custom';


  columnDefs = [
    { headerName: "Make", field: "make" ,resizable: true,filter: true  },
    { headerName: "Model", field: "model",resizable: true ,filter: true  },
    { headerName: "Price", field: "price",resizable: true ,filter: true  }
  ];

  rowData = [
    { make: "Toyota", model: "Celica", price: 35000 },
    { make: "Ford", model: "Mondeo", price: 32000 },
    { make: "Porsche", model: "Boxter", price: 72000 }
  ];

}

In the app.component.html file add the below snippet

<div>
  <ag-grid-angular style="width: 100%; height: 500px;" class="ag-theme-alpine" [rowData]="rowData"
    [columnDefs]="columnDefs">
  </ag-grid-angular>
</div>

Output

Github

https://github.com/rkumar9090/ag-grid

Categories
Angular

Interceptor in angular

Interceptor in angular will intercept each http request and response also error

Syntax

interface HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>>
}

CLI command to create interceptor

Once you created the angular application, naviagate to root folder and execute below command to create interceptor

ng g interceptor (name)

Now a class will be created as like below

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request);
  }
}

The class should implement HttpInterceptor interface. The method intercept will handle the request and response

You should add this interceptor in your app module.ts file in the provider section as like below

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AgGridModule } from 'ag-grid-angular';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { MyappintercepInterceptor } from './myappintercep.interceptor';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AgGridModule.withComponents([]),
    AppRoutingModule
  ],
  providers: [{provide: HTTP_INTERCEPTORS, useClass: MyappintercepInterceptor, multi: true }  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

You have to clone the request to add token in the http request headers as like below

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class MyappintercepInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {

    request = request.clone({
      setHeaders: {
        'apptoken': 'SYSTEM'
      }
    });
    
    return next.handle(request);
  }
}

Categories
pandas python

create dataframe in python using pandas

In this post, we will learn about create dataframe in python using pandas. There are multiple ways to create dataframe in python

DataFrame

Dataframe is one of the data types in python as like string, int. It will look like a table.

It consists of rows and columns. We can say that it is a two-dimensional array.

Here we are using pandas to create the data frame. Pandas is a fast and powerful open-source package.
For More details refer the doc below
https://pandas.pydata.org/

Installing Pandas Libraries using pip

pip install pandas

Installing Pandas libraries using conda

conda install pandas

In order to use pandas, we should install a pandas package on our machine.
Open the terminal/Command prompt and run any one of the above commands
Once you installed we need to import using the import command below

import pandas as pd

Here I am going to create a data frame with avengers details as like below image

Below are the multiple ways to create dataframe in python using pandas.

  • Create data frame from list
  • Create data frame using dictionary
  • Create data frame from csv file
  • Load Mysql table as dataframe using pandas
  • Load Mongodb collection as dataframe
1. Create data frame from list
import pandas as pd

avengers_column_details = ['ID', 'Character Name', 'Real Name']
avengers_data = [[1, 'Hulk', 'Mark Ruffalo'], [2, 'Thor', 'Chris Hemsworth'], [3, 'Black Widow', 'Scarlett Johansson'], [4, 'Iron Man', 'Robert Downey Jr'],[5, 'Captain America', 'Chris Evans']]

df_avengers_details = pd.DataFrame(avengers_data, columns=avengers_column_details)
print("Created Dataframe using List")
print(df_avengers_details)
Output using list
 Created Dataframe using List
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans

In the above example, we have created a data frame using the list.

2. Create data frame using dictionary
import pandas as pd

dict_avengers_data={"ID": [1, 2, 3, 4, 5],
                    "Character Name": ['Hulk', 'Thor', 'Black Widow', 'Iron Man', 'Captain America'],
                    "Real Name": ['Mark Ruffalo', 'Chris Hemsworth', 'Scarlett Johansson', 'Robert Downey Jr', 'Chris Evans']}
df_avengers_dict = pd.DataFrame(dict_avengers_data)
print("Created Dataframe using dict")
print(df_avengers_dict)
Output
Created Dataframe using dict
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans

Here we are created a data frame using the dictionary. Printed the output.

3. Create data frame from csv file

In the below code, we are importing a CSV file as a data frame with the help of pandas library

import pandas as pd

df_avenger_data_csv = pd.read_csv("D://avenger_details.csv")
print("Created Dataframe using csv file")
print(df_avenger_data_csv)
print("\n")
Output
Created Dataframe using csv file
    ID   Character Name           Real Name
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans
4. Load Mysql table as dataframe using pandas

To load the MySQL table data as a data frame we need a MySQL connector library. you can install using the below command

 pip install mysql-connector-python

Once you installed the MySQL connector in your system. you need to create the MySQL connection object and need to pass the connection object and query to the pandas as below

import pandas as pd
import mysql.connector

mysql_connection = mysql.connector.connect(host="localhost", user="root", password="password", database="avengers")
df = pd.read_sql("select * from avengersdetails", mysql_connection)
print("Created Dataframe from mysql table")
print(df)
mysql_connection.close()
Output
Created Dataframe from mysql table
    ID    CharacterName            RealName
 0   1             Hulk        Mark Ruffalo
 1   2             Thor     Chris Hemsworth
 2   3      Black Widow  Scarlett Johansson
 3   4         Iron Man    Robert Downey Jr
 4   5  Captain America         Chris Evans
5. Load Mongodb collection as dataframe

To load the MongoDB collection data as a data frame we need pymongo library. you can install using the below command

pip install pymongo

Once you installed the pymongo in your system. you need to create the MongoDB connection object. After that, you need to convert MongoDB to pandas data frame

For connecting python with MongoDB refer this
https://beginnersbug.com/python-with-mongodb/

import pandas as pd
import pymongo

mongodb_connection = pymongo.MongoClient("mongodb://localhost:27017/")
mongodb_db = mongodb_connection["avengers"]
mongodb_avengers = mongodb_db["avengersdetails"].find()
df_mongodb_avengers = pd.DataFrame(list(mongodb_avengers))
print("Created Dataframe from mongodb collections")
print(df_mongodb_avengers)
Output
Created Dataframe from mongodb collections
                         _id ID   Character Name           Real Name
 0  5fd0e603549a851a24a48c36  1             Hulk        Mark Ruffalo
 1  5fd0e603549a851a24a48c37  2             Thor     Chris Hemsworth
 2  5fd0e603549a851a24a48c38  3      Black Widow  Scarlett Johansson
 3  5fd0e603549a851a24a48c39  4         Iron Man    Robert Downey Jr
 4  5fd0e603549a851a24a48c3a  5  Captain America         Chris Evans
Related Articles
Categories
Angular

pass value between two components using the route in angular

In this tutorial, we will learn about pass value between two components using the route in angular

In many scenarios, we need to pass one or two parameters from one component to another component

We can pass a value in various ways, But in this tutorial, we go to pass value between components using the route

For this tutorial, We are going to pass student id from the student list on click

By default, we will define routing as like below in-app-routing.module.ts

{ path: 'student', component: StudentDetailsComponent }

We need to pass id along with the student route like /student/1from the student list page

We can receive those route param value in student details page using ActivatedRoute

import { ActivatedRoute } from '@angular/router';
Sending value from first component

Here we are using pass value while clicking a hyperlink. via router link, we are defining the student id value as like below

<a [routerLink]="['/student', studentId]">{{name}} </a>
Routing Syntax

We need to mention in app.routing.module.ts about the parameter as like below
{ path: 'student/:id', component: StudentDetailsComponent }

app.routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { StudentDetailsComponent } from './component/student-details/student-details.component';


const routes: Routes = [
  { path: 'student/:id', component: StudentDetailsComponent }
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }
Receiving value in second component

As mentioned above we are going to use activedRoute to retrieve the value

this.studentId = this.activeParms.snapshot.paramMap.get("id");
Student-details-component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({

  selector: 'app-student-details',
  templateUrl: './student-details.component.html',
  styleUrls: ['./student-details.component.css']
})
export class StudentDetailsComponent implements OnInit {

  constructor(private activeParms: ActivatedRoute) { }
  studentId: string;
  ngOnInit(): void {
    this.studentId = this.activeParms.snapshot.paramMap.get("id");
  }

}
Conclusion

In this post, we looked about to pass value between two components using the route in angular

Related Articles

https://beginnersbug.com/ng-if-else-condition-in-angular-with-example/