Tuesday, November 20, 2012

Insertion Sort

class InsertionSorting
{
  public static void main(String a[])
{
  int i;
  int array[] = {12,9,4,99,120,1,3,10};
    System.out.println("Values Before the sort:\n"); 
  for(i = 0; i < array.length; i++)
  System.out.print( array[i]+"  ");
  System.out.println();
  insertion_srt(array, array.length); 
  System.out.print("Values after the sort:\n"); 
  for(i = 0; i <array.length; i++)
  System.out.print(array[i]+"  ");
  System.out.println();
 
  }

  public static void insertion_srt(int array[], int n)
{
  for (int i = 1; i < n; i++)
{
  int k = i;
  int M = array[i];
  while ((k > 0) && (array[k-1] > M))
{
  array[k] = array[k-1];
  k--;
  }
  array[k] = M;
  }
  }
}

No comments: