第二篇算法。
选择排序,也是非常简单的排序算法,学校课本中学过。
定义如下:首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到所有元素均排序完毕。(摘自维基百科)
Java语言实现:
int[] arrays = {34, 32, 22, 82, 55, 89, 50, 37, 5, 3};
System.out.println("y: " + Arrays.toString(arrays));
int size = arrays.length;
for (int i = 0; i < size - 1; ++i){
int t = i;
for (int j = i+1; j < size ; ++j){
if (arrays[t] > arrays[j]){
t = j;
}
}
int tmp = arrays[t];
arrays[t] = arrays[i];
arrays[i] = tmp;
System.out.println( i + ": " + Arrays.toString(arrays));
}
输出的结果为:
y: [34, 32, 22, 82, 55, 89, 50, 37, 5, 3]
0: [3, 32, 22, 82, 55, 89, 50, 37, 5, 34]
1: [3, 5, 22, 82, 55, 89, 50, 37, 32, 34]
2: [3, 5, 22, 82, 55, 89, 50, 37, 32, 34]
3: [3, 5, 22, 32, 55, 89, 50, 37, 82, 34]
4: [3, 5, 22, 32, 34, 89, 50, 37, 82, 55]
5: [3, 5, 22, 32, 34, 37, 50, 89, 82, 55]
6: [3, 5, 22, 32, 34, 37, 50, 89, 82, 55]
7: [3, 5, 22, 32, 34, 37, 50, 55, 82, 89]
8: [3, 5, 22, 32, 34, 37, 50, 55, 82, 89]
如果想要将最大的排到最前面,需要将
if (arrays[t] > arrays[j])
改为:
if (arrays[t] < arrays[j])
修改后的输出如下:
y: [34, 32, 22, 82, 55, 89, 50, 37, 5, 3]
0: [89, 32, 22, 82, 55, 34, 50, 37, 5, 3]
1: [89, 82, 22, 32, 55, 34, 50, 37, 5, 3]
2: [89, 82, 55, 32, 22, 34, 50, 37, 5, 3]
3: [89, 82, 55, 50, 22, 34, 32, 37, 5, 3]
4: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
5: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
6: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
7: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
8: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
发现在 4 时就已经排好顺序了。
可以对此进行优化,加入flag的判断:
int[] arrays = {34, 32, 22, 82, 55, 89, 50, 37, 5, 3};
System.out.println("y: " + Arrays.toString(arrays));
int size = arrays.length;
for (int i = 0; i < size - 1; ++i){
int t = i;
boolean flag = true;
for (int j = i+1; j < size ; ++j){
if (arrays[t] < arrays[j]){
t = j;
flag = false;
}
}
int tmp = arrays[t];
arrays[t] = arrays[i];
arrays[i] = tmp;
System.out.println( i + ": " + Arrays.toString(arrays));
if (flag){
break;
}
}
优化后的输出结果如下:
y: [34, 32, 22, 82, 55, 89, 50, 37, 5, 3]
0: [89, 32, 22, 82, 55, 34, 50, 37, 5, 3]
1: [89, 82, 22, 32, 55, 34, 50, 37, 5, 3]
2: [89, 82, 55, 32, 22, 34, 50, 37, 5, 3]
3: [89, 82, 55, 50, 22, 34, 32, 37, 5, 3]
4: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
5: [89, 82, 55, 50, 37, 34, 32, 22, 5, 3]
可以看到,少几次的循环。