11 Dec 2017

Write a program for Insertion Sort.



public class InsertionSort {
          public static void main(String a[]) {
                   int[] arr1 = { 2, 5, 2, 8, 5, 6, 6, 6, 8, 8 };
                   int[] arr2 = doInsertionSort(arr1);
                   System.out.println("Sorted List is::");
                   for (int i : arr2) {
                             System.out.print(i);
                             System.out.print(", ");
                   }
          }

          public static int[] doInsertionSort(int[] input) {

                   int temp;
                   for (int i = 1; i < input.length; i++) {
                             for (int j = i; j > 0; j--) {
                                      if (input[j] < input[j - 1]) {
                                                temp = input[j];
                                                input[j] = input[j - 1];
                                                input[j - 1] = temp;
                                      }
                             }
                   }
                   return input;
          }
}


Output:

Sorted List is::

2 2 5 5 6 8 8 8