1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
public class SelectionSort {
public static void main(String[] args) {
System.out.println("Selection,Sort!");
Integer[] a = { 8, 2, 3, 1, 4, 6, 7, 5 };
selection(a);
System.out.println(Arrays.toString(a));
}
private static void exchange(Comparable[] a, int i, int j) {
Comparable temp;
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
private static boolean greater(Comparable v, Comparable w) {
return v.compareTo(w) > 0;
}
private static void selection(Comparable[] a) {
for (int i = 0; i < a.length-1; i++) {
int minIndex = i;
for (int j = i+1; j < a.length; j++) {
if (greater(a[minIndex], a[j])) {
// exchange(a, minIndex, j); we can not exchange here,see i as assistant point every time need to move forward.
minIndex = j;
}
}
exchange(a, i, minIndex);
}
}
}
|