public class ArraySorter
2: /**
3: Class for sorting an array of base type int from smallest to largest.
4: */
5: public class ArraySorter
6: {
7: /**
8: Precondition: Every element in anArray has a value.
9: Action: Sorts the array into ascending order.
10: */
11: public static void selectionSort(int[] anArray)
12: {
13: for (int index = 0; index < anArray.length - 1; index++)
14: { // Place the correct value in anArray[index]
15: int indexOfNextSmallest = getIndexOfSmallest(index, anArray);
16: interchange(index, indexOfNextSmallest, anArray);
17: //Assertion:anArray[0] <= anArray[1] <=...<= anArray[index]
18: //and these are the smallest of the original array elements.
19: //The remaining positions contain the rest of the original
20: //array elements.
21: }
22: }
23:
24: /**
25: Returns the index of the smallest value in the portion of the
26: array that begins at the element whose index is startIndex and
27: ends at the last element.
28: */
29: private static int getIndexOfSmallest(int startIndex, int[] a)
30: {
31: int min = a[startIndex];
32: int indexOfMin = startIndex;
33: for (int index = startIndex + 1; index < a.length; index++)
34: {
35: if (a[index] < min)
36: {
37: min = a[index];
38: indexOfMin = index;
39: // Assertion: min is smallest of a[startIndex] through a[index]
40: }
41: }
42: return indexOfMin;
43: }
45: /**
46: Precondition: i and j are valid indices for the array a.
47: Postcondition: Values of a[i] and a[j] have been interchanged.
48: */
49: private static void interchange(int i, int j, int[] a)
50: {
51: int temp = a[i];
52: a[i] = a[j];
53: a[j] = temp; //original value of a[i]
54: }
55: }
56: