码迷,mamicode.com
首页 > 编程语言 > 详细

排序算法: 插入排序

时间:2018-09-22 17:05:58      阅读:116      评论:0      收藏:0      [点我收藏+]

标签:复杂度   main   算法分析   需要   class   算法   using   排序   i++   

算法分析

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

  

 

排序算法: 插入排序

标签:复杂度   main   算法分析   需要   class   算法   using   排序   i++   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!