原理
实现
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::swap;
using std::vector;
void selectSort(vector<int>& nums) {
int minIndex; //定义变量保存最小值所在位置
for (int i = 0; i < nums.size() - 1; i++) { //因为要与后面未排序的比较找最小值,所以最多比对N-1轮
minIndex = i; //内循环是每轮要比较的次数,所以在每轮比较前将本轮第一个位置预设为最小值的位置
for (int j = i + 1; j < nums.size(); j++) {
if (nums[minIndex] > nums[j]) { //如果有比预设最小值还小的存在,则把该值的位置设置为最小值位置
minIndex = j;
}
}
//交换当前值与最小值的位置
swap(nums[i], nums[minIndex]);
}
}
void print(const vector<int>& nums) {
for (int i = 0; i < nums.size(); i++) {
cout << nums[i] << " ";
}
cout << endl;
}
void test() {
vector<int> nums = { 1,4,7,2,5,8 };
print(nums);
selectSort(nums);
print(nums);
}
int main() {
test();
return 0;
}
性能
- 不稳定排序
- 序列5 8 5 2 9, 我们知道第⼀遍选择第1个元素5会和2交换,那么原序列中2个5的相对前后顺序就被破坏了,所以选择排序不是⼀个稳定的排序算法。
- 时间复杂度:O(n^2)
- 空间复杂度:O(1)
- 原地排序