排序算法: 插入排序

算法分析

(1)时间复杂度

从时间来看,排序的基本操作为:比教两个关键字的大小移动记录。

#include<iostream>
#include<vector>
using namespace std;
void InsertSort(int a[], int n)
{
	for (int i = 1; i < n; i++)
	{
		if (a[i] < a[i - 1])//如果小于已经排好序的最后一个元素,则需要把元素插入
			//已经排好序的序列中,否则就不需要移动
		{
			int key = a[i];
			//a[i] = a[i - 1];
			int j = i - 1;
			for (; key < a[j]; j--)
			{
				a[j + 1] = a[j];
			}
			a[j + 1] = key;
		}
	}
}
int main()
{
	int a [11] = { 2,6,4,5,54,53,53,5,34,34,32};
	InsertSort(a, 11);
	for (int i = 0; i < 11; i++)
	{
		cout << a[i] << " ";
	}
	return 0;
}

  

原文地址:https://www.cnblogs.com/wuyepeng/p/9690334.html