Java - 二进制插入排序,故障排除

时间:2017-02-19 11:06:20

标签: java arrays binary-search

我有一个任务,我需要使用二进制插入排序对数组进行排序。 这是我提出的解决方案,但它太慢了:

public static void binaryInsertionSort(int[] a) {
    int ins, i, j;
    int tmp;
    for (i = 1; i < a.length; i++) {
        ins = BinarySearch (a, 0, i, a[i]);
            if(ins < i) {
                tmp = a[i];
                for (j = i - 1; j >= ins; j--)
                    a[j+1] = a[j];
                a[ins] = tmp;
            } 
    }   
}

private static int BinarySearch(int[] a, int low, int high, int key) {

    int mid;
    if (low == high)
        return low;
    mid = low + ((high - low) / 2);
    if (key > a[mid])
        return BinarySearch (a, mid + 1, high, key);
    else if (key < a[mid])
        return BinarySearch (a, low, mid, key);
    return mid;

}

我被建议使用我尝试过的System.arraycopy方法,但我不明白它为什么不起作用:

public static void binaryInsertionSort(int[] a) {
    int ins, i;
    int tmp = a[i];
    for (i = 1; i < a.length; i++) {
        ins = binarySearch (a, 0, i, a[i]);
            if(ins < i){
                System.arraycopy(a, ins, a, ins + 1, i - ins);
                a[ins] = tmp;
            } 
    }   
}

private static int binarySearch(int[] a, int low, int high, int key) {
    int mid;
    if (low == high)
        return low;
    mid = low + ((high - low) / 2);
    if (key > a[mid])
        return binarySearch (a, mid + 1, high, key);
    else if (key < a[mid])
        return binarySearch (a, low, mid, key);
    return mid;
}

任何帮助都有帮助。

1 个答案:

答案 0 :(得分:0)

嗯,与此同时,答案比我想象的要容易。  我在错误的地方初始化了局部变量。而不是:

public static void binaryInsertionSort(int[] a) {
int ins, i, j;
**int tmp = a[i];**
    for (i = 1; i < a.length; i++) {
        ins = BinarySearch (a, 0, i, a[i]);
            if(ins < i){
                tmp = a[i];
                for (j = i - 1; j >= ins; j--)
                a[j+1] = a[j];
                a[ins] = tmp;
            } 
    }   
}

正确的方法是:

public static void binaryInsertionSort(int[] a) {
    int ins, i;
        for (i = 1; i < a.length; i++) {
            **int tmp = a[i];**
            ins = binarySearch (a, 0, i, a[i]);
                if(ins < i){
                    System.arraycopy(a, ins, a, ins + 1, i - ins);
                    a[ins] = tmp;
                } 
    }   
}

它有效(: