现在的位置: 首页 > 综合 > 正文

【基础排序】直接插入排序

2013年10月24日 ⁄ 综合 ⁄ 共 478字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;
void Insert_sort(int a[],int n)
{
	for(int i=1;i <= n; i++)
	{
		if(a[i] < a[i-1])
		{
			int temp = a[i];
			for(int j=i-1; a[j]>temp; j--)
			{
				a[j+1] = a[j];
			}
			a[j+1] = temp;
		}
	}
}

void print(int a[],int n)
{
	for(int i=0; i<n; i++)
	{
		cout<<a[i]<<" ";
	}
	cout << endl;
}

void main()
{
	int a[] = {1,3,6,8,0,5,7};
	cout << "排序前:";
	print(a,sizeof(a)/sizeof(a[0]));
	Insert_sort(a,sizeof(a)/sizeof(a[0]));
	cout << "排序后:";
	print(a,sizeof(a)/sizeof(a[0]));
}

排序前:1 3 6 8 0 5 7
排序后:0 1 3 5 6 7 8
Press any key to continue

 

 

最差时间复杂度O(n^2)

平均时间复杂度O(n^2)

 

 

抱歉!评论已关闭.