思想:
遍历数组,选择找到最大值,记录最大值下标maxindax,然后将最大值与最后一个值交换,即swap(vec[maxindax],vec[n-1]);
在剩下的待排序数组中,重新找到最大值,重复第一步,swap(vec[maxidnax],vec[n-2]),循环操作,直至数组排序完成。
代码:
#include<iostream>
#include<vector>
using namespace std;
void selectSort(vector<int>&vec,int n)
{
//j代表是待排序数组的个数,下标对应就是0到j-1
for (int j = n; j >= 1; j--)
{
int max = vec[0];
int maxindax = 0;
for (int i = 0; i < j; i++)
{
if (vec[i] > max)
{
//找到最大数,并且记录下标maxIndax
max = vec[i];
maxindax = i;
}
}
//交换最大值与待排序数组的最后一个
swap(vec[maxindax], vec[j - 1]);
}
}
int main()
{
vector<int>vec = { 2,3,5,8,9,7,4,6,1 };
selectSort(vec, vec.size());
for (auto it : vec)
{
cout << it << " ";
}
return 0;
}
时间复杂度:
第一次排序时是n个元素,比较n-1次
第二次排序时是n-1个元素,比较n-2次
...
第n-1次排序时是2个元素,比较1次
第n次排序时是1个元素,比较0次
元素交换次数为k(k<n-1次)
时间复杂度=比较次数+交换次数
故选择排序时间复杂度为O(1+2+3+...+n-1+k)=O(n*(n-1)/2+k)=O(n2)
空间复杂度:
在原数组上操作,即使用了常数级空间O(1)。
稳定性
稳定性是指排序之后相同的数相对位置不变。
实例:3 2 3 1 从小到大排序(选择最小的放前面),排序之后第二个3在第一个3前面,所以不稳定。
投稿来自 东北石油大学 - 大数据 201 - 金树正