You are here:   HomeJava ProgrammingJava ArrayDeleting Desire Element of Linked List Java Example
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.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





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes 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.



What's New and Popular





Popular Article