Monday, December 16, 2013

Sorting Simplified: Insertion Sort

Hi All,

I am putting the code for insertion sort. You can either pass the numbers to be sorted via command-line or through GUI. Code is pasted below. Please mail me if you need further details...
+++++++++++++
package examples;

import javax.swing.JOptionPane;

/**
 * @author Akash Mahakode
 * @email akash.mahakode@gmail.com
 *
 */
public class InsertionSort {

//pseudocode
/*
 for j= 2 to A.length
{
      key = A[j]
      i = j-1
      while (i > 0 & A[i] > key)
     {
        A[i+1] = A[i]
        i = i-1
     }
     A[i+1] = key
}
*/
public static void main(String[] args) {
     int [] inputArray;
     if(args.length == 0){
          String str = JOptionPane.showInputDialog(null, "Please enter numbers to be sorted, \n seperate                               them by space");
          String array[] = str.split(" ");
          inputArray = new int[array.length];
          for (int i = 0; i < array.length; i++) {
          inputArray [i] = Integer.parseInt(array[i]);
          }
     }else{
               inputArray = new int[args.length];
               for (int i = 0; i < args.length; i++) {
               inputArray [i] = Integer.parseInt(args[i]);
     }
  }
insertionSort(inputArray);
}

private static void insertionSort(int[] inputArray) {
     System.out.println("Input Array is : ");
     String tempStrInput = "";
     String tempStrOutput = "";
     for (int i = 0; i < inputArray.length; i++) {
          System.out.print(inputArray[i]+ "  ");
          tempStrInput = tempStrInput + " " +inputArray[i];
     }
     //start : main algorithm implementation
     for(int j = 1; j < inputArray.length ; j ++){
          int key = inputArray[j];
          int i = j -1;
          while (i > -1 && inputArray[i] > key) {
               inputArray[i+1] = inputArray[i];
               i = i -1;
          }
     inputArray[i+1] = key;
}
//end : man algorithm implementation
     System.out.println();
     System.out.println("Sorted array is : ");
     for (int i = 0; i < inputArray.length; i++) {
          System.out.print(inputArray[i]+ "  ");
          tempStrOutput = tempStrOutput + " " +inputArray[i];
          }
JOptionPane.showMessageDialog(null, "Input : \n"+tempStrInput+"\n\n Output: \n "+tempStrOutput);
     }


}
++++++++++++