算法(1)插入排序

来源:互联网 发布:现货市场开户软件 编辑:程序博客网 时间:2024/06/03 04:03

        最近在看《算法导论》,想着将其中涉及到的算法都实现一遍,这是第一篇,也是刚刚开始。

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

        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,moveelsebreak;       //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;}

原创粉丝点击