question1-在插入排序中运用二元搜索代替线性查找

int insertionSort(int *x, int n){
    int i = 0, j = 0, k = 0, target = 0;
    for(i = 0; i < n-1; i++){
        target = x[i+1];
        j = binaryInsert(x, 0, i, target);  //找出需要插入的 位置j
        for(k = i; k > j; k--)         //更改数据 ? T(n) = ?
            x[k+1] = x[k];
        x[j+1] = target;
    }
    for(i = 0; i < n; i++)
        cout<<"x["<<i<<"] = "<<x[i]<<endl;
    return 0;
}

int binaryInsert(int *x, int p, int q, int target){
    if(p > q)
        return q;
    else{
        int mid = (p+q)/2;
        if(x[mid] < target)
            return binaryInsert(x, mid+1, q, target);
        else if(x[mid] > target)
            return binaryInsert(x, p, mid-1, target);
        else
            return mid;
    }
}

int test(void){
    int x[] = {3,2,1};
    int n = (sizeof x)/4;
    insertionSort(x, n);
    return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页