/**
* SelectionSort.java
*
* A class to demonstrate selection sorting.
*
* Created: Sun Feb 16 15:07:55 2003
*
* @author Stuart C. Shapiro
*/
public class SelectionSort {
/**
* Sorts the integer array a, using selection sort.
*
* post: a[j] <= a[j+1], 0 <= j < a.length.
*
* @param a an int
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].
*
* post: a[i]@post == a[j]@pre and a[j]@post == a[i]@pre.
*
* @param a an int[]
value
* @param i an int
value
* @param j an int
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 int[]
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 String[]
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