Insertion Sort
Write a program to sort an array using Insertion Sort technique. In this technique, array is traversed in a reverse order starting from the second index and each time an element's proper position in a part of the array is checked.
import java.util.*;
class InsertionSort{
public static void main(String args[])throws InputMismatchException{
Scanner scan=new Scanner(System.in);
int n,i,j,k,t;
System.out.println("Enter the number of elements : ");
n=scan.nextInt();
int a[]=new int[n]; //declare array
System.out.println("Enter "+n+" elements.");
for(i=0;i < n;i++)
a[i]=scan.nextInt();
//sort the array in ascending order
for(i=0;i< n;i++){
k=a[i];
for(j=i-1;j>=0 && k< a[j];j--){
a[j+1]=a[j];
}//end of inner loop
a[j+1]=k;
}//end of outer loop
//display the sorted array
for(i=0;i< n;i++){
System.out.println(a[i]+" ");
}//end of loop
}//end of main
}//end of class
Have something to say? Log in to comment on this post.
0 comments