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

public class SelectionSort {

    /**
     * Sorts the integer array a, using selection 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 = 0; next < a.length-1; next++) {
	    /* a[0 .. next] is sorted.
	     * a[0 .. next-1] <= a[next .. a.length-1].
	     * a[next .. length-1] is to be sorted. */
	    int min = next;
	    for (int j = next+1; j < a.length; j++) {
		if (a[j] < a[min]) {min = j;}
	    }
	    // a[min] is minimum of a[next .. length-1].
	    swap(a, next, min);
		}
    }

    /**
     * Swaps the values of a[i] and a[j].
     * <p>
     * post: a[i]@post == a[j]@pre and a[j]@post == a[i]@pre.
     *
     * @param a an <code>int[]</code> value
     * @param i an <code>int</code> value
     * @param j an <code>int</code> value
     */
    private static void swap(int[] a, int i, int j) {
	int temp = a[i];
	a[i] = a[j];
	a[j] = temp;
    }

    /**
     * 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 Selection 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 ()
    
    
}// SelectionSort
