Friday, July 26, 2013

Insertion Sort in Java


This is a simple implementation of insertion sort in java which can be useful for reference purpose. It takes an array as input, sort that array using insertion sort logic and prints the output.

public class InsertionSort {

    public static void main(String...args) {
        int[] a={1,5,2,9,8,3,4,5};
        int key,i;
        for(int j=1; j< a.length;j++) {
          key = a[j];
          i=j-1;
          while(i>=0 && a[i] > key) {
              a[i+1]=a[i];
              i=i-1;
          }
          a[i+1]=key;
        }
       
        for(int a1:a) {
          System.out.println(a1);
        }
    }
}
 


No comments:

Post a Comment