import java.util.*;
/**
 * Insertion sort routine for arrays
 * @author Suzanne Balik, 6 Nov 2001
 */

public class InsertionSort {

  public static void sort(int[] array) {
  
    for (int i = 1; i < array.length; i++) {
    
      int toBeInserted = array[i];
      
      int j;
      
      for (j = i - 1; j >= 0 && toBeInserted < array[j]; j--)
      
        array[j + 1] = array[j];
	
      array[j + 1] = toBeInserted;
    }
  }
  
  public static String toString(int[] array) {
  
    String s = "[";
    for (int i = 0; i < array.length; i++)
      s += " " + array[i];
    s += " ]";
    return s;
  }
  
  public static void main(String[] args) {
  
    int[] array = {2, 8, 1, 3, 4, 5, 7, 6};
    
    System.out.println("Unsorted array: " + 
                        InsertionSort.toString(array));
    InsertionSort.sort(array);
    
    System.out.println("Sorted array:   " + 
                        InsertionSort.toString(array));
    if (args.length == 1) { 
      array = new int[Integer.parseInt(args[0])];
      Random generator = new Random();
      final int MAX = 200;
      for (int i = 0; i < array.length; i++)
        array[i] = generator.nextInt(MAX);
      long startTime = System.currentTimeMillis();
      InsertionSort.sort(array);
      long stopTime = System.currentTimeMillis();
      System.out.println("Time to sort " + args[0] + 
                         " random integers in range 1 - 200: " + 
			 (stopTime - startTime) + "ms");
      
    }
  }
}