public class Main {
public static void main(String[] args) {
int[] values = {3, 1, 2};
int i = 0;
while (i < 2) {
int smallest = i;
int j = i + 1;
while (j < 3) {
if (values[j] < values[smallest]) {
smallest = j;
}
j += 1;
}
int saved = values[i];
values[i] = values[smallest];
values[smallest] = saved;
i += 1;
}
i = 0;
while (i < 3) {
System.out.println(values[i]);
i += 1;
}
}
}
输出
1
2
3
生活中的例子
先装较轻的包裹
三个包裹分别重8、3和5千克。第一个装车的位置该放哪个?
初始状态8 3 5
结果3 8 5
把三个包裹都看一遍,再把重量为3的包裹与最前面的包裹交换。
找出最早的日期
未整理的表格上分别写着 9 日、12 日、4 日。按日期整理时,哪一天的表应放进第一个托盘?
初始状态9 12 4
结果4
如果只看前两张表上的日期,就会漏掉 4 日。
直接在书架上整理图书
书 1 和 2 的位置已经定好,只剩下书 5 和 3。接下来要检查哪一段?
初始状态1 2 • 5 3
结果1 2 3 5
已经排好的前段不用动。从剩下的那一对中选3,把它放到该在的位置。
开销与局限
即使剩下的元素已经有序,选择排序仍会把它们检查一遍。需要O(n²)次比较,最多交换n−1次。
时间复杂度
最好情况: Θ(n²)
平均情况: Θ(n²)
最坏情况: Θ(n²)
用 Java 实现选择排序
Java 源代码
class SelectionSortExample {
public void selectionSort(int[] arr) {
int length = arr.length;
for(int i = 0; i < length - 1; i++) {
int minIndex = i;
for(int j = i + 1; j < length; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public void printArray(int[] arr) {
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
SelectionSortExample obj = new SelectionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.selectionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
广告
一步步看例子
从 [15, 3, 12, 6, -9, 9, 0] 开始。
从下标0开始。扫描剩下的值,记住最小值(−9)所在的位置。
交换两个值:−9和第一项15。第一项的位置就确定了。
从下一个位置重复。只剩一项时,整个数组就已经排好序。
用 Java 实现选择排序:逐步讲解
Java 源代码
class SelectionSortExample {
public void selectionSort(int[] arr) {
// Get the length of an array
int length = arr.length;
// Loop all the element in an array except the last element
for(int i = 0; i < length - 1; i++) {
int minIndex = i;
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for(int j = i + 1; j < length; j++) {
if(arr[minIndex] > arr[j]) {
minIndex = j;
}
}
// Swap the lowest element with the current element (i.e. arr[i] <=> arr[minIndex])
int temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
public void printArray(int[] arr) {
// Loop the item and print each item in the console with white space seperated
for(int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("");
}
public static void main(String[] args) {
SelectionSortExample obj = new SelectionSortExample();
int[] arr = { 15, 3, 12, 6, -9, 9, 0 };
System.out.print("Before Sorting: ");
obj.printArray(arr);
obj.selectionSort(arr);
System.out.print("After Sorting: ");
obj.printArray(arr);
}
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15