选择排序:找到数组中最小的元素记录它的索引,然后将它和数组的第一个元素交换,在剩下的元素找出最小的元素与第二个元素交换。如此往复,直到将数组排序

排序工具

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
/**
* 检查 a 是否小于 b
*/
public boolean less(Comparable a, Comparable b) {
return a.compareTo(b) < 0;
}

/**
* 交换 c 中索引为 i 和 j 的元素
*/
public void exch(Comparable[] c, int i, int j) {
Comparable t = c[i];
c[i] = c[j];
c[j] = t;
}

/**
* 检查 c 是否已排序
*/
public void isSorted(Comparable[] c) {
for (int i = 1; i < c.length; i++>) {
if (less(c[i], c[i - 1])) {
throw new RuntimeException("Not Sorted");
}
}
}

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Selection {
public static void sort(Comparable[] com) {
int n = com.length;
for (int i = 0; i < n; i++) {
int min = i;
for (int j = i + 1; j < n; j++) {
if (less(com[j], com[min])) {
min = j;
}
}
exch(com, min, i);
}
}
}

测试

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
* 使用 apache RandomUtils 生成测试数据
*/
public static void main(String[] args) {
Comparable[] random = new Comparable[20];
for (int i = 0; i < 20; i++) {
random[i] = RandomUtils.nextInt(1, 10);
}
sort(random);
for (int i = 0; i < 20; i++) {
System.out.print(random[i]);
if (i != random.length - 1) {
System.out.print(" | ");
}
}
isSorted(random);
}