Insertion Sort


package com.kartik.sorting;
/**
 *
 * @author MandalKC
 *
 */
public class InsertionSort {
 /**
  *
  * @param input
  * @return
  */
    public static int[] doInsertionSort(int[] input){
     System.out.println("Before Insertion Soring --->>");
  printNumbers(input);
  System.out.println("After Insertion Soring start--->>");
        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;
                }
            }
            printNumbers(input);
        }
        return input;
    }
    /**
     *
     * @param input
     */
    private static void printNumbers(int[] input) {
  for (int i = 0; i < input.length; i++) {
   System.out.print(input[i] + ", ");
   } System.out.println("\n");
  }
   
    /**
     *
     * @param a
     */
    public static void main(String a[]){
        int[] arr1 = {10,34,2,56,7,67,88,42};
         doInsertionSort(arr1);
       // int[] arr2 = doInsertionSort(arr1);
        /*for(int i:arr2){
            System.out.print(i);
            System.out.print(", ");
        }*/
    }
}


Out Put:

Before Insertion Soring --->>



10, 34, 2, 56, 7, 67, 88, 42,





After Insertion Soring start--->>


10, 34, 2, 56, 7, 67, 88, 42,





2, 10, 34, 56, 7, 67, 88, 42,





2, 10, 34, 56, 7, 67, 88, 42,





2, 7, 10, 34, 56, 67, 88, 42,





2, 7, 10, 34, 56, 67, 88, 42,





2, 7, 10, 34, 56, 67, 88, 42,





2, 7, 10, 34, 42, 56, 67, 88,
Previous
Next Post »