Ad

Friday 3 April 2015

How to implement insertion sort algorithm in java

In this post we will see how to implement the insertion sort algorithm in java with a sample program.In insertion sorting
  1. we will select a key from the array for each iteration ,which will start from index 1 of the array to the last element.
  2. The key will be compared with the elements precedence to it (i.e if the key selected is at index 2,it will be compared with the elements at index 1 and index 0) and the key will be inserted at the right position in the array.
Below sample program will explain this in detail.

package test;

public class InsertionSortSample {

public static void main(String[] args) {
int[] arry = new int[] { 20, 3, 150, 5, 6, 78, 2, 123, 43, 45, 99, 1,
12 };
InsertionSortSample insertionSort = new InsertionSortSample();
insertionSort.sort(arry);
}

public void sort(int[] arry) {
printElements(arry);
int len = arry.length;
int key = 0;
int j=0;
for (int i = 1; i < len; i++) {
key=arry[i];
j=i-1;
while(j>=0 && key<arry[j])
{
arry[j+1]=arry[j];
j--;
}
arry[j+1]=key;
printElements(arry);
}

}

public void printElements(int[] arry) {
for (int i = 0; i < arry.length; i++) {
System.out.print("  " + arry[i]);
}
System.out.println();
}

}

When we run the above program,we will ge this output

  20  3  150  5  6  78  2  123  43  45  99  1  12
  3  20  150  5  6  78  2  123  43  45  99  1  12
  3  20  150  5  6  78  2  123  43  45  99  1  12
  3  5  20  150  6  78  2  123  43  45  99  1  12
  3  5  6  20  150  78  2  123  43  45  99  1  12
  3  5  6  20  78  150  2  123  43  45  99  1  12
  2  3  5  6  20  78  150  123  43  45  99  1  12
  2  3  5  6  20  78  123  150  43  45  99  1  12
  2  3  5  6  20  43  78  123  150  45  99  1  12
  2  3  5  6  20  43  45  78  123  150  99  1  12
  2  3  5  6  20  43  45  78  99  123  150  1  12
  1  2  3  5  6  20  43  45  78  99  123  150  12
  1  2  3  5  6  12  20  43  45  78  99  123  150

Above output will show the array elements position at the end of each iteration and how the key is inserted at the right position.

No comments:

Post a Comment