插入排序

步骤
  1.1、首先对数组的前两个数据进行从小到大的排序
  2.2、接着将第3个数据与排好的两个数据比较,将第3个数据插入到合适的位置
  2.3、然后,将第4个数据插入到已排序好的前3个数据
  2.4、不断重复上述的过程。

// InsertSort.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include<IOSTREAM>
#include<CSTDIO>
#include<CSTDLIB>
#include<CSTRING>
#include<CTIME>

using namespace std;


#define  SIZE 10

void InsertSort(int *a, int len)
{
	int i, j, t, h;

	for (i = 1; i < len; i++)
	{
		t = a[i];
		j = i -1;
		while(j >= 0 && t < a[j])
		{
			a[j+1] = a[j];
			j--;
		}
		a[j+1] = t;

		cout<<"sort "<<i<<" step result"<<endl;
		
		for (h = 0; h < len; h++)
		{
			cout<<a[h]<<" ";
		}	
		cout<<endl;
	}

}

int main(int argc, char* argv[])
{
	int array[SIZE], i = 0;
	
	srand(time(NULL));
	for (;i < SIZE; i++)
	{
		array[i] = rand() /1000 + 100;
	}
	
	cout<<"before sort -------------"<<endl;
	for (i = 0; i < SIZE; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;
	InsertSort(array, SIZE);
	
	cout<<"Sort: ------------------"<<endl;
	for (i = 0; i < SIZE; i++)
	{
		cout<<array[i]<<" ";
	}
	cout<<endl;

	getchar();
	return 0;
}



before sort -------------
113 119 127 100 113 106 110 117 107 121
sort 1 step result
113 119 127 100 113 106 110 117 107 121
sort 2 step result
113 119 127 100 113 106 110 117 107 121
sort 3 step result
100 113 119 127 113 106 110 117 107 121
sort 4 step result
100 113 113 119 127 106 110 117 107 121
sort 5 step result
100 106 113 113 119 127 110 117 107 121
sort 6 step result
100 106 110 113 113 119 127 117 107 121
sort 7 step result
100 106 110 113 113 117 119 127 107 121
sort 8 step result
100 106 107 110 113 113 117 119 127 121
sort 9 step result
100 106 107 110 113 113 117 119 121 127
Sort: ------------------
100 106 107 110 113 113 117 119 121 127



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值