折半插入排序

/**
 * Copyright (C) 2015, CSU
 * All rights reserved
 * File Name:test.cpp
 * Author: lmm
 * Date of completion: 2015/1/19
 * Version: v1.0
 *
 * 问题描述:折半插入排序
 * 输入描述: 输入整数
 * 知识点  : 内部排序
 * 程序输出: 输出有序整数
 */

#include <iostream>
#include <stdio.h>
using namespace std;

void BInsertSort(int *seqList,int length)
{
    // seqList[0]设置为监视哨,避免数组下标出界,并且存放的是当前比较中的小者
    int i, j;
    int low,high,mid;
    for (i = 2 ; i < 11; ++i)           // 比较的趟数
    {
        seqList[0] = seqList[i]; // 将seqList[i]暂放在seqList[0]处,seqList[i]即待排序插入的数
        low = 1;
        high = i - 1;           // 不包括当前位置,从前i-1个位置去找
        // 折半查找寻找插入位置
        while(low <= high)
        {
            mid = (low+high) / 2;
            if(seqList[0] < seqList[mid])
                high = mid - 1;   // 插入点在低半区
            else
                low = mid + 1;    // 插入点在高半区
        }
        // 已找到插入位置,high+1 或者 low-1 从插入位置到i-1之间的记录依次后移
        for(j = i - 1; j >= high + 1; --j)
            seqList[j+1] = seqList[j];
        seqList[high+1] = seqList[0];  // 将待插入记录插入正确的位置
    }
}
int main()
{
    int a[11] = {0};
    int result[10] = {0};
    int seqNum = 0;
    cout << "Input ten numbers: ";
    for (int i = 1; i < 11; ++i)  // 输入10个数,result[0]为哨兵
    {
        cin >> seqNum;
        a[i] = seqNum;
    }
    BInsertSort(a,11);            // 折半插入排序
    cout << endl << "Output the results: ";
    for (int j = 0, i = 1; j < 10 && i < 11; ++i,++j)
    {
        result[j] = a[i];
        cout << result[j] << " ";
    }
    cout << endl;
    return 0;

}

程序结果输出:


折半插入排序时间复杂度为

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值