您的位置:首页 > 其它

算法(1)插入排序

2017-11-30 16:00 232 查看
        最近在看《算法导论》,想着将其中涉及到的算法都实现一遍,这是第一篇,也是刚刚开始。

        插入排序的算法大致是这样的,好比打牌,将桌上的牌在手上实现排序。

        1.从桌上拿一张牌

        2.从后向前与手中的牌面大小进行比较。若相比更小,则说明还没有到插入的位置,手上的此牌右移一位。

        3.若相比大,则插入到此牌的前一张。

        4.重复1-3,直到桌面无牌为止。

        代码实现如下
#include <iostream>

using namespace std;

void insert_sort(int *a,int len)
{
int temp,j;
for(int i=1;i<len;i++) //the remain card
{
temp=a[i];
for(j=i-1;j>=0;j--) //card in hand ,search from the back
{
if(temp<a[j])
a[j+1]=a[j]; //find? no,move
else
break; //find? yes.this a[j]>temp,so temp should be put in a[j+1]
}
a[j+1]=temp;

}
}

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

int main()
{
int array[10]={2,6,1,44,22,7666,2,4,6,19};
show_array(array,10);
insert_sort(array,10);
show_array(array,10);
return 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: