Insertion sort sort of foundation

The main idea: the number of columns is divided into front and rear portions, the front portion of the order, the disordered portion, the sequence of random values ​​sequentially inserted into the rear face of the front ordered sequence; initially ordered sequence is in front of the first element; implemented still two nested loops.

Time complexity: O (N ^ 2);

 

demo:

#include<iostream>
#include<vector>
using namespace std;
//插入排序  时间复杂度 O(n^2)
//数列前部分看为有序,依次将后面无序部分数列插入
void my_swap(int& first, int& second)
{
	int tmp = first;
	first = second;
	second = tmp;
}
void InserttionSort(vector<int>& vec)
{
	int len = vec.size();
	for (int i = 0; i < len-1; i++)
	{
		//前i个元素为有序的
		for (int j = i + 1; j > 0; j--)
		{
			//与有序序列中的元素依次比较,直到遇到更小的,则停下
			if (vec[j] < vec[j - 1])
				my_swap(vec[j], vec[j - 1]);
			else
				break;//不需要交换,j到了合适的位置
		}
	}
}
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;

	InserttionSort(arr);
	cout << "InsertionSorted 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/103076385