算法思想
- 对于一个序列num中的元素num[0]~num[n-1],令i从0到n-1枚举,进行n趟操作。
- 每趟从待排序部分[i,n-1]中选择最小的元素,令其与待排序部分的第一个元素num[i]进行交换。这样元素num[i]就会与当前有序区间[0,i-1]形成新的有序区间[0,i]。
- 于是在n趟操作后,所有的元素就会是有序的。[1]
代码实现
C++
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
using namespace std;
void select_sort(vector<int> &num)
{
for (auto i = 0; i < num.size(); ++i)
{
// 有序区间[0,i-1] 无序区间[i,num.size()-1]
int min_idx = i; // 无序区间中最小元素的下标
for (auto j = i; j < num.size(); ++j)
{
if (num[j] < num[min_idx])
{
min_idx = j;
}
}
// 最小元素与num[i]交换 使有序区间扩充为[0,i]
int tmp = num[i];
num[i] = num[min_idx];
num[min_idx] = tmp;
}
}
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
// 测试算法
vector<int> a, a_copy;
vector<int> b, b_copy;
b = b_copy = {1, 2, 4, 0, 8, 7};
vector<int> c, c_copy;
c = c_copy = {9, 9, 9, 8, 8, 3, 1, 3};
select_sort(a), sort(a_copy.begin(), a_copy.end());
select_sort(b), sort(b_copy.begin(), b_copy.end());
select_sort(c), sort(c_copy.begin(), c_copy.end());
cout << (a == a_copy) << endl;
cout << (b == b_copy) << endl;
cout << (c == c_copy) << endl;
assert(a == a_copy);
assert(b == b_copy);
assert(c == c_copy);
return 0;
}
参考文献
[1] 《算法笔记》 胡凡 曾磊