Program for Insertion Sort in Java

In this tutorial we have given the source code for Insertion Sort Java Program with the output. Insertion Sorting is a very simple sorting algorithm that builds the final sorted array with one item at a time. So in this source code of Insertion sort program, we have applied this algorithm with java syntax for Insertion Sort technique.

Insertion Sort Java Program Source Code

public class InsertionSort {

   public static void main(String args[]) {

     int[] x = {597, 21, 523, 1378, 243, 774, 14, 93, 510};
     System.out.println("Unsorted list: ");
     display(x);

     insertion(x);
     System.out.println("Sorted list: ");
     display(x);
   }

   private static void insertion(int x[]) {

     int i, k, y;

     for (k=1; k<x.length; k++) {
       y=x[k];

       for(i=k-1; i>=0 && y<x[i]; i--)
         x[i+1] = x[i];

       x[i+1]=y;
     }
   }

   private static void display(int x[]) {
     for (int i=0; i<x.length; i++)
       System.out.print(x[i] + " ");
     System.out.println("\n");
   }
}

Output of Insertion Sort Program 

In the output or screenshot of Insertion sort program, you can see that we have taken 9 elements of an array to sort by Insertion sort and after that it displays the correct sorted order through insertion sort technique.
 

0 comments:

Post a Comment