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