- //折半插入排序
- void sortInsertHalf(int t[],int size,int style)
- {
- int *b = new int[size+1];
- b[0] = 0;
- for (int k=0;k<size;k++)
- {
- b[k+1] = t[k];
- }
- for (int i=2;i<size+1;i++)
- {
- b[0] = b[i];//b[0]为哨兵
- int low=1;
- int high=i-1;
- while (low<=high)
- {
- int m = (low+high)/2;// 折半
- if (1 == style)
- {
- if(b[0] < b[m]){
- high = m-1; //插入点在低半区
- }else{
- low = m+1;// 插入点在高半区
- }
- }
- else
- {
- if(b[0] > b[m]){
- high = m-1; //插入点在低半区
- }else{
- low = m+1;// 插入点在高半区
- }
- }
- }
- for (int j=i-1;j>=low;--j)
- {
- b[j+1] = b[j];
- }
- b[high+1] = b[0];
- }
- //将b又赋值到t
- for (int x=1;x<size+1;x++)
- {
- t[x-1] = b[x];
- }
- delete[] b;
- }
折半插入排序c++实现
/*
*折半插入排序:数组的第一个元素li[0]作为哨兵
*"折半插入"不失为是一条减少关键字比较次数的途径,
* 并不能介绍记录移动次数
*/
#include <iostream>
using std::cout;
using std::endl;
// 对顺序表L作折半插入排序
void BInsertSort(int *L){
for(int i=2; i<=8; ++i ){
L[0] = L[i];//将L[i]暂存到L[0]
int low = 1;
int high = i-1;
while (low <= high){// 在r[low..high]中折半查找有序插入的位置
int m = (low+high)/2;// 折半
if(L[0] < L[m]){
high = m-1; //插入点在低半区
}else{
low = m+1;// 插入点在高半区
}
}
for(int j=i-1; j>=low; --j ){
L[j+1] = L[j];// 记录后移
}
L[high+1] = L[0];// 插入
}
} // BInsertSort
int main()
{
int li[9] = {0,7,8,4,5,6,1,2,3};//li[0]作为哨兵,比较li[1....8]
for(int i = 1; i<=9; i++){
cout << li[i-1] << " ";
}
cout << endl;
BInsertSort(li);
for(int i = 1; i<=9; i++){
cout << li[i-1] << " ";
}
cout << endl;
return 0;
}
转载于:https://blog.51cto.com/shpshao/453687