/**
* 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;
}
程序结果输出:
折半插入排序时间复杂度为