Insertion sort algorithm simple explanation with example

Insertion sort in java. Inserttion sort algorithm is explained here, with an example on sorting an array. The main idea of insertion sort is to repeatedly find the next  smallest number and move it to the starting position, if the sorting is  to be in ascending (increasing) order. Read other sorting algorithms like insertion sort and bubble sort along with this which helps you to understand sorting algorithms in clear.

Explanation:

Take an array consist of four numbers {72,18,8,90}

Now, we gonna sort this array in ascending order using selection sort algorithm.

First time in for loop:

  a[0]=72 and a[1]=18.  72 is greater than 18 so, the while loop condition is satisfied and the numbers are swapped inside while loop.
 Now, 18 is moved to the index zero in the array.

Second loop:

  Now, a[1]=72 and a[2]=8.  72 is greater than 8 so, the while loop condition is satisfied till it move 8 to the first position ie index zero in the array.

Third loop:

  72 is not greater than 90 so, the while is not satisfied.

   The array is now sorted as follow {8,18,72,90}.

 

IMPLEMENTATION IN JAVA:

class insertionSort
{
  public static void main(String args[])
    {
		int a[]={72,18,90,12,22,8};
		for(int i=0;i < a.length-1;i++)
		  {
		  	int j=i;
		  	while(j > =0 && a[j] > a[j+1])
		  	{
		  	int	temp=a[j];
		  		a[j]=a[j+1];
		  		a[j+1]=temp;
		  		j--;
		  	}
		  }
		  		for(int i=0;i < a.length;i++)

				{
	                          System.out.println(a[i]);
				}
     }
 }
	
	  

 

RESULT:

8
12
18
22
72
90

Insertion sort -Descending order

 

class insertionSort
{
  public static void main(String args[])
    {
		int a[]={72,18,90,12,22,8};
		for(int i=0;i < a.length-1;i++)
		  {
		  	int j=i;
		  	while(j > =0 && a[j] < a[j+1])
		  	{
		  	int	temp=a[j];
		  		a[j]=a[j+1];
		  		a[j+1]=temp;
		  		j--;
		  	}
		  }
		  		for(int i=0;i < a.length;i++)

				{
	                          System.out.println(a[i]);
				}
     }
 }