public class SortArray
1: /**
2: A class of static, iterative methods for sorting an array of
3: Comparable objects from smallest to largest.
4:
5: @author Frank M. Carrano
6: @author Timothy M. Henry
7: @version 4.0
8: */
9: public class SortArray
10: {
11: /** Sorts the first n objects in an array into ascending order.
12: @param a An array of Comparable objects.
13: @param n An integer > 0. */
14: public static <T extends Comparable<? super T>> void selectionSort(T[] a, int n)
15: {
16: for (int index = 0; index < n - 1; index++)
17: {
18: int indexOfNextSmallest = getIndexOfSmallest(a, index, n - 1);
19: swap(a, index, indexOfNextSmallest);
20: // Assertion: a[0] <= a[1] <= . . . <= a[index] <= all other a[i]
21: } // end for
22: } // end selectionSort
23:
24: // Finds the index of the smallest value in a portion of an array a.
25: // Precondition: a.length > last >= first >= 0.
26: // Returns the index of the smallest value among
27: // a[first], a[first + 1], . . . , a[last].
28: private static <T extends Comparable<? super T>>
29: int getIndexOfSmallest(T[] a, int first, int last)
30: {
31: T min = a[first];
32: int indexOfMin = first;
33: for (int index = first + 1; index <= last; index++)
34: {
35: if (a[index].compareTo(min) < 0)
36: {
37: min = a[index];
38: indexOfMin = index;
39: } // end if
40: // Assertion: min is the smallest of a[first] through a[index].
41: } // end for
42:
43: return indexOfMin;
44: } // end getIndexOfSmallest
45:
46: // Swaps the array entries a[i] and a[j].
47: private static void swap(Object[] a, int i, int j)
48: {
49: Object temp = a[i];
50: a[i] = a[j];
51: a[j] = temp;
52: } // end swap
53: } // end SortArray