1 /**
2 This class sorts an array, using the selection sort
3 algorithm
4 */
5 public class SelectionSorter
6 {
7 private int[] a;
8
9 /**
10 Constructs a selection sorter.
11 @param anArray the array to sort
12 */
13 public SelectionSorter(int[] anArray)
14 {
15 a = anArray;
16 }
17
18 /**
19 Sorts the array managed by this selection sorter.
20 */
21 public void sort()
22 {
23 for (int i = 0; i < a.length - 1; i++)
24 {
25 int minPos = minimumPosition(i);
26 swap(minPos, i);
27 }
28 }
29
30 /**
31 Finds the smallest element in a tail range of the array.
32 @param from the first position in a to compare
33 @return the position of the smallest element in the
34 range a[from] . . . a[a.length - 1]
35 */
36 private int minimumPosition(int from)
37 {
38 int minPos = from;
39 for (int i = from + 1; i < a.length; i++)
40 if (a[i] < a[minPos]) minPos = i;
41 return minPos;
42 }
43
44 /**
45 Swaps two entries of the array.
46 @param i the first position to swap
47 @param j the second position to swap
48 */
49 private void swap(int i, int j)
50 {
51 int temp = a[i];
52 a[i] = a[j];
53 a[j] = temp;
54 }
55 }