基础排序算法之选择排序

主体: 遍历,找到最小元素,记录索引,遍历完后将最小元素与首元素交换;

时间复杂度: 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;
}

输出结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值