by Dinesh Thakur

Algorithm for Insertion Sort:

Here 'a' is an array of elements and 'n' represents the number of elements in the array 'a'

step 1: Initialize j= 1

step 2: repeat through step-8 while(j<n)

step 3: set item =a[j]

step 4: set i=j-l

step 5: repeat through step-7 while(i>=0 && item < a[i])

step 6: a[i+ I]=a[i]

step 7: Increment the value of 'i' as i-1

step 8: Increment the value of ’j' as j+ 1

step 9: Exit

Here is the Java Example for Insertion Sort:

import java.util.Scanner;

public class InsertionSort
{
                     static int a[];
                     static int n;
                          public static void main(String args[])
                    {
                          Scanner read=new Scanner(System.in);
                          System.out.print("Enter Number of Elements you want to Insert : ");
                          n=read.nextInt();
                          a=new int[n];
                          for(int i=0;i<n;i++)
                               {
                                     System.out.print("\nEnter no. "+(i+1)+" ");
                                     a[i]=read.nextInt();
                               }
                                     InsertionSort ii=new InsertionSort();
                                     ii.insertionsort(a,n);
                                    System.out.print("\nAll Elements are :");
                                    for(int i=0;i<n;i++)
                                             {
                                                  System.out.print(a[i]+" ");
                                             }
                       }
                               void insertionsort(int a[],int n)
                                     {
                                         int i,j,item;
                                         for(j=1;j<n;j++)
                                             {
                                                  item=a[j];
                                                  for(i=j-1;i>=0&&item<a[i];i--)
                                                  a[i+1]=a[i];
                                                  a[i+1]=item;
                                              }
                                       }
}

Insertion Sort