排序之基于数组插入排序

有n个元素,其中前m个已经有序,后n-m个是无序状态,使用选择排序毫无意义,于是使用一种新的方法插入排序。

设有一个数组List如下:

List={10,18,25,30,23,17,45,35};

List[4]应该插入List[1]和List[2]之间,先把List[4]->temp,List[2]和List[3]后移,再temp->List[2]。

我们在排序过程中,把整个数组分为两个部分,前面有序的一部分和后面无序的一部分,把无序的部分插入有序的部分。

对于任意的一个无序表,我们把无序表第一个数的index设为1即,firstOutOfOrderIndex=1;通过第一次插入,由元素0和1组成了一个有序表,2~n成了一个无序表,进行插入排序。

void insertSort()
{
    for(firstOutOfOrder=1;firstOutOfOrder<length;firstOutOfOrder++)
    if(List[firstOutOfOrder]<item[firstOutOfOrder-1])
    {
        temp=List[firstOutOfOrder];
        insertIndex=firstOutOfOrder;
        do
        {
            List[insertIndex]=List[insertIndex-1];
            insertIndex--;
        }
        while(List[insertIndex-1]>temp&&insertIndex>0)
            List[insertIndex]=temp;
    }
}

以下是基于数组的插入排序具体实现

#include <iostream>

using namespace std;

int main()
{
    int List[10]={22,3,45,1,87,99,42,42,54,67};
    for(int firstOutOfOrderIndex=1;firstOutOfOrderIndex<10;firstOutOfOrderIndex++)
    {
        if(List[firstOutOfOrderIndex]<List[firstOutOfOrderIndex-1])
        {
            int temp=List[firstOutOfOrderIndex];
            int insertIndex=firstOutOfOrderIndex;
            do
            {
                List[insertIndex]=List[insertIndex-1];
                insertIndex--;
            }
            while(List[insertIndex-1]>temp&&insertIndex>0);
                List[insertIndex]=temp;
        }
    }
    for(int i=0;i<10;i++)
        cout<<List[i]<<endl;
    return 0;
}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值