by Dinesh Thakur Category: array

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.out.print("Enter Number of Elements you want to Insert : ");
                          a=new int[n];
                          for(int i=0;i<n;i++)
                                     System.out.print("\nEnter no. "+(i+1)+" ");
                                     InsertionSort ii=new InsertionSort();
                                    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;

Insertion Sort

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles