思想
- 找到数组中最小的元素
- 将它和数组中的第一个元素交换位置(如果最小元素是自己,那么就和自己交换)
- 在剩下的元素中找到最小的元素,将它与数组的第二个元素进行交换。
- 如此往复,直到将整个数组排序
i | min | 0 | 1 | 2 | 3 | 4 |
---|
| | 7 | 3 | 9 | 5 | 1 |
0 | 4 | 7 | 3 | 9 | 5 | 1 |
1 | 1 | 1 | 3 | 9 | 5 | 7 |
2 | 3 | 1 | 3 | 9 | 5 | 7 |
3 | 4 | 1 | 3 | 5 | 9 | 7 |
4 | 4 | 1 | 3 | 5 | 7 | 9 |
| | 1 | 3 | 5 | 7 | 9 |
实现步骤
public class Selection {
public static void sort(int[] a) {
int N = a.length;
for (int i = 0; i < N; i++) {
int min = i;
for (int j = i + 1; j < N; j++)
if (less(a[j], a[min])) min = j;
exch(a, i, min);
}
}
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
private static void exch(int[] a, int i, int j) {
Comparable t = a[i];
a[i] = a[j];
a[j] = (int) t;
}
private static void show(int[] a) {
for (int i = 0; i < a.length; i++)
System.out.println(a[i]);
}
public static boolean isSorted(int[] a) {
for (int i = 1; i < a.length; i++)
if (less(a[i], a[i - 1]))
return false;
return true;
}
public static void main(String[] args) {
int[] a = init.random(1000);
Stopwatch time = new Stopwatch();
sort(a);
double timer = time.elapsedTime();
if (isSorted(a)) {
show(a);
System.out.println("time: " + timer);
}
else System.out.println("false");
}
}