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 5.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>>
15: void selectionSort(T[] a, int n)
16: {
17: for (int index = 0; index < n - 1; index++)
18: {
19: int indexOfNextSmallest = getIndexOfSmallest(a, index, n - 1);
20: swap(a, index, indexOfNextSmallest);
21: // Assertion: a[0] <= a[1] <= . . . <= a[index] <= all other a[i]
22: } // end for
23: } // end selectionSort
24:
25: // Finds the index of the smallest value in a portion of an array a.
26: // Precondition: a.length > last >= first >= 0.
27: // Returns the index of the smallest value among
28: // a[first], a[first + 1], . . . , a[last].
29: private static <T extends Comparable<? super T>>
30: int getIndexOfSmallest(T[] a, int first, int last)
31: {
32: T min = a[first];
33: int indexOfMin = first;
34: for (int index = first + 1; index <= last; index++)
35: {
36: if (a[index].compareTo(min) < 0)
37: {
38: min = a[index];
39: indexOfMin = index;
40: } // end if
41: // Assertion: min is the smallest of a[first] through a[index].
42: } // end for
43:
44: return indexOfMin;
45: } // end getIndexOfSmallest
47: // Swaps the array entries a[i] and a[j].
48: private static void swap(Object[] a, int i, int j)
49: {
50: Object temp = a[i];
51: a[i] = a[j];
52: a[j] = temp;
53: } // end swap
54: } // end SortArray