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

直接插入排序

时间:2017-09-03 14:55:35      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:log   blog   include   class   turn   name   插入   位置   div   

//直接插入排序
#include<iostream>
using namespace std;
const int  MAXN = 10;

int main()
{
	int a[MAXN];
	int n;
	int j;
	cin >> n;//要排的数的个数

	for (int i = 0; i < n; i++)//存到数组里
		cin >> a[i];

	for (int i = 1; i < n; i++)
	{
		int temp = a[i];//将要插的数取出来,数存给temp
		j = i;//当前坐标给j,j是移动的坐标标记

		//将要插入的数倒着跟前面有序的数比较,有序的数如果大于temp,就后移

		while (a[j - 1] > temp&&j > 0)//如果a[j-1]>要插的数(temp)且j至少是1才进行循环操作
		{
			a[j] = a[j - 1];//条件满足,a[j-1]后移,为啥用temp存a[j](a[i])
			j--;//往前再比较,标记得移动
		}
		a[j] = temp;//将插的数放到符合的位置j处
	}

	for (int i = 0; i < n; i++)
		cout << a[i] << " ";
	cout << endl;

	return 0;
}

 

直接插入排序

标签:log   blog   include   class   turn   name   插入   位置   div   

原文地址:http://www.cnblogs.com/dusanlang/p/7469502.html

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