Home >>Java Programs >Java Program for insertion sort
In this example, we will create a java program to sort array elements using insertion sort. Insertion sort algorithm is good for small elements only because it requires more time for sorting the large number of elements.
Program:
public class Main
{
public static void insertionSort(int array[])
{
int n = array.length;
for (int j = 1; j < n; j++)
{
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) )
{
array [i+1] = array [i];
i--;
}
array[i+1] = key;
}
}
public static void main(String a[]){
int[] arr1 = {9,14,31,72,43,91,58,23,48,83,39};
System.out.println("Before Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
insertionSort(arr1);//sorting array using insertion sort
System.out.println("After Insertion Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}