We are uploading our contents, please refresh app.
Java Premium

write a program in java do Insertion Sort algorithm using array

Insertion sort is a simple sorting algorithm suited for small data sets. During each iteration, the algorithm

    Removes an element from an array
    Compares it against the largest value in the array
    Moves the element to its correct location.

Here is how the process works graphically

Program:
public class InsertionSortExample
{
public static void main(String a[])
    {   
        int[] myArray  = {6,5,3,1,8,7,2,4}; 
        System.out.println("Before Insertion Sort"); 
        printArray(myArray);
        insertionSort(myArray);//sorting array using insertion sort   
        System.out.println("After Insertion Sort"); 
        printArray(myArray);  
    }   
 public static void insertionSort(int arr[])
 { 
        int n = arr.length; 
        for (int i = 1; i < n; i++)
        {   System.out.println("Sort Pass Number "+(i));
            int key = arr[i]; 
            int j = i-1; 
            while ( (j > -1) && ( arr [j] > key ) )
            { 
            System.out.println("Comparing "+ key  + " and " + arr [j]);
                arr [j+1] = arr [j]; 
                j--; 
            } 
            arr[j+1] = key;
            System.out.println("Swapping Elements: New Array After Swap");
            printArray(arr);
        } 
    }
 static void printArray(int[] array)
 {
   for(int i=0; i < array.length; i++)
  { 
   System.out.print(array[i] + " "); 
  }
     System.out.println();
 }
}
Output:
Before Insertion Sort
6 5 3 1 8 7 2 4
Sort Pass Number 1
Comparing 5 and 6
Swapping Elements: New Array After Swap
5 6 3 1 8 7 2 4
Sort Pass Number 2
Comparing 3 and 6
Comparing 3 and 5
Swapping Elements: New Array After Swap
3 5 6 1 8 7 2 4
Sort Pass Number 3
Comparing 1 and 6
Comparing 1 and 5
Comparing 1 and 3
Swapping Elements: New Array After Swap
1 3 5 6 8 7 2 4
Sort Pass Number 4
Swapping Elements: New Array After Swap
1 3 5 6 8 7 2 4
Sort Pass Number 5
Comparing 7 and 8
Swapping Elements: New Array After Swap
1 3 5 6 7 8 2 4
Sort Pass Number 6
Comparing 2 and 8
Comparing 2 and 7
Comparing 2 and 6
Comparing 2 and 5
Comparing 2 and 3
Swapping Elements: New Array After Swap
1 2 3 5 6 7 8 4
Sort Pass Number 7
Comparing 4 and 8
Comparing 4 and 7
Comparing 4 and 6
Comparing 4 and 5
Swapping Elements: New Array After Swap
1 2 3 4 5 6 7 8
After Insertion Sort
1 2 3 4 5 6 7 8

Online user

Download our android app Download App Submit your query
x

Get Updates On

Java & Premium Programs

Java Solved & Questions

Java Coding easy to use

Proper Coding

Straight Into Your INBOX!

We are going to send you our resources for free. To collect your copy at first, join our mailing list. We are promising not to bother you by sending useless information. So don't miss any updates, stay connected!