文章目录
2021/8/6打卡算法排序【选择排序】
选择排序(英语:Selection sort)是排序算法的一种,它的工作原理是每次找出第 i 小的元素(也就是 Ai…n 中最小的元素),然后将这个元素与数组第 i 个位置上的元素交换。
稳定性
由于 swap(交换两个元素)操作的存在,选择排序是一种不稳定的排序算法。
代码实现
void selection_sort(int* a, int n) {
for (int i = 0; i < n-1; ++i) {
int ith = i;
for (int j = i + 1; j <= n; ++j) {
if (a[j] < a[ith]) {
ith = j;
}
}
swap(a[i],a[ith]);
}
}