#include <stdbool.h>
#include <stdio.h>
int main(void) {
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) {
printf("%d\n", values[i]);
i += 1;
}
}
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。第一项的位置就确定了。
从下一个位置重复。只剩一项时,整个数组就已经排好序。
用 C 实现选择排序:逐步讲解
C 源代码
#include<stdio.h>
int selectionSort(int arr[], size_t size) {
// Loop all the element in an array except the last element
for(size_t i = 0; i < size - 1; i++) {
int minIndex = i;
// Find an index of a lowest element in the right-hand side
// corresponding to the element arr[i].
for(size_t j = i + 1; j < size; 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;
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
selectionSort(arr, SIZE);
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
输出
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15