主体: 遍历,找到最小元素,记录索引,遍历完后将最小元素与首元素交换;
时间复杂度: O(N^2);
过程: 两个循环,外循环从前往后遍历每一个元素,内层循环找到子序列中的最小值的索引,并将最小值与子序列的首元素值交换;
选择 --》 选择最小索引;
demo:
#include<iostream>
#include<vector>
using namespace std;
//选择排序
//依次遍历查找最小元素的索引值
void my_swap(int& first, int& second)
{
int tmp = first;
first = second;
second = tmp;
}
void SelectionSort(vector<int>& vec)
{
int len = vec.size();
int min_index;
for (int i = 0; i < len; i++)
{
min_index = i;
for (int j = i+1; j<len; j++)
{
if (vec[j] < vec[min_index])
min_index = j;
}
if(min_index != i)
my_swap(vec[i], vec[min_index]);
}
}
int main()
{
vector<int> arr = { 12,5,9,34,3,97,63,23,53,87,120,11,77 };
cout << "raw val is:\n";
for (auto i : arr)
cout << i << "\t";
cout << endl;
SelectionSort(arr);
cout << "BubbleSorted val is:\n";
for (auto i : arr)
cout << i << "\t";
cout << endl;
system("pause");
return 0;
}
输出结果: