折半插入排序C/C++

void BinaryInsertionSort(int a[],int left,int right);

//对数组a[left]到a[right]段数据从小到大排序
void BinaryInsertionSort(int a[],int left,int right)
{
    int low,middle,high;
    int temp;
    int i,j;
    //待排元素left+1 ---> right 共right - left个,a[left]默认有序
    for (i=left+1;i<=right;i++){    
        temp = a[i];
        low = left;        
        high = i - 1;    //i-1为已排好序列的右边界
        while(low<=high){
            middle = (low + high) / 2;
            if (a[i]<a[middle])    //应当将a[i]插入左半区
                high = middle - 1;
            else                //应当将a[i]插入右半区
                low = middle + 1;
        }
        //插入位置为low,low位置及其后的元素后移一位(i-1为已排好序列的右边界)
        for (j=i-1;j>=low;j--)
            a[j+1] = a[j];
        a[low] = temp;
    }
}

/*算法分析:
    time-complexity: 折半插入排序在查找插入位置时花费的时间很少,但移动次数与直接插入排序次数一样,
                     最差情况下时间复杂度为O(n2),最好情况下为O(nlog2n);
                     平均情况下为O(n2);
    space-complexity: O(1);
    算法不稳定.
*/

 

posted @ 2018-04-17 21:19  蝉鸣的Summer  阅读(520)  评论(0编辑  收藏  举报