1. //折半插入排序  
  2. void sortInsertHalf(int t[],int size,int style)  
  3. {  
  4.     int *b = new int[size+1];  
  5.     b[0] = 0;  
  6.     for (int k=0;k<size;k++)  
  7.     {  
  8.         b[k+1] = t[k];  
  9.     }  
  10.  
  11.       
  12.     for (int i=2;i<size+1;i++)  
  13.     {  
  14.         b[0] = b[i];//b[0]为哨兵  
  15.         int low=1;  
  16.         int high=i-1;  
  17.         while (low<=high)  
  18.         {  
  19.             int m = (low+high)/2;// 折半  
  20.             if (1 == style)  
  21.             {  
  22.                 if(b[0] < b[m]){  
  23.                     high = m-1;  //插入点在低半区  
  24.                 }else{  
  25.                     low = m+1;// 插入点在高半区  
  26.                 }  
  27.             }   
  28.             else  
  29.             {  
  30.                 if(b[0] > b[m]){  
  31.                     high = m-1;  //插入点在低半区  
  32.                 }else{  
  33.                     low = m+1;// 插入点在高半区  
  34.                 }  
  35.             }  
  36.         }  
  37.         for (int j=i-1;j>=low;--j)  
  38.         {  
  39.             b[j+1] = b[j];  
  40.         }  
  41.         b[high+1] = b[0];  
  42.     }  
  43.  
  44.     //将b又赋值到t  
  45.     for (int x=1;x<size+1;x++)  
  46.     {  
  47.         t[x-1] = b[x];  
  48.     }  
  49.  
  50.     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;

}