Select the basic sorting algorithm to sort

Body: traversal, find the smallest element, the index record, after traversing the smallest element with the first element of exchange;

Time complexity: O (N ^ 2);

Process: two loops, the outer loop from front to back through each element, the inner loop minimum is found in the index sequence, and the minimum value of the first element and the switching sequence;

Select - "Select a minimum index;

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;
}

Output:

 

Published 69 original articles · won praise 10 · views 30000 +

Guess you like

Origin blog.csdn.net/u010096608/article/details/103076237