/**
 * InsertionSort.java
 * <br>
 * A class to demonstrate insertion sorting.
 * <br>
 * Created: Sun Feb 16 15:07:55 2003
 *
 * @author <a href="mailto:shapiro@cse.buffalo.edu">Stuart C. Shapiro</a>
 */

public class InsertionSort {

    /**
     * Sorts the integer array a, using insertion sort.
     * <p>
     * post: a[j] <= a[j+1], 0 <= j < a.length.
     *
     * @param a an <code>int</code> array to be sorted.
     */
    public static void sort(int[] a) {
	for (int next = 1; next < a.length; next++) {
	    /* a[0 .. next-1] is sorted.
	     * a[next] is to be inserted. */
	    int temp = a[next];
	    int j = next;
	    while (--j >= 0 && a[j] > temp) {
		a[j+1] = a[j];
	    } // end of while (j >= 0 && a[j] > temp)
	    // j == -1 or a[j] <= temp
	    a[j+1] = temp;
	    } // for (int next = 1; next < a.length; next++)
    }

    /**
     * Prints an array to System.out, followed by a newline.
     *
     * @param a an <code>int[]</code> to be printed.
     */
    private static void arrayPrintln (int[] a) { 
	System.out.print("\t{" + a[0]);
	for (int j = 1; j < a.length; j++) {System.out.print(", " + a[j]);}
	System.out.println("}");
    }

    /**
     * Tests the sort method.
     *
     */
    private static void test(int[] a) {
	System.out.print("Original: ");
	arrayPrintln(a);
	System.out.print("Sorted: ");
	sort(a);
	arrayPrintln(a);
    }

    /**
     * Demonstrates Insertion Sort.
     *
     * @param args a <code>String[]</code> value
     */
    public static void main (String[] args) {
	test(new int[] {345,75,72,88,2,75,45,756,187,73,724,952,457});
    } // end of main ()
    
    
}// InsertionSort
