插入排序

来源:互联网 发布:淘宝会员等级表 编辑:程序博客网 时间:2024/06/08 13:16

我理解的插入排序的基本思想是:对于新插入的数,通过寻找其在有序序列中的合适位置 达到排序的目的。下面是实现的代码

#include <iostream>
using namespace std;


void insert_sort(int a[],int n)
{
int j;
for (int i=0;i<n;i++)
{
int temp = a[i];      //用于存放要插入的数
for(j=i;j>0 && a[j-1]>temp;j--)  //将要插入的数和前面的有序序列比较,寻找合适的插入位置
{
a[j]=a[j-1];
}
a[j]=temp;
}
}


void main()
{
int a[] = {4,6,12,9,3,66,3,5,9,98};
insert_sort(a,10);
for (int i = 0;i<10;i++)
{
cout<<a[i]<<"->";
}
system("Pause");
}


0 0