我的heapsort只在阵列的某些间隔排列

时间:2012-03-29 23:10:44

标签: java sorting

我遇到了heapsort的问题。它似乎只安排了每个4的间隔。我的输出是:

167548
1092841
11047435
23672988
3901457
13705876
32329454
62936411
34097325
45417546
23189907
50261310
184562247

代码:

public static <T extends Comparable<? super T>> void reheap(T[] heap, int rootIndex, int lastIndex) {

    boolean done = false;
    T orphan = heap[rootIndex];
    int leftChildIndex = 2 * rootIndex + 1;

    while (!done && (leftChildIndex <= lastIndex)) {
        int largerChildIndex = leftChildIndex;
        int rightChildIndex = leftChildIndex + 1;
        if ((rightChildIndex <= lastIndex) && heap[rightChildIndex].compareTo(heap[largerChildIndex]) > 0) {
            largerChildIndex = rightChildIndex;
        }

        if (orphan.compareTo(heap[largerChildIndex]) < 0) {
            heap[rootIndex] = heap[largerChildIndex];
            rootIndex = largerChildIndex;
            leftChildIndex = 2 * rootIndex + 1;

        } else
            done = true;
    }
    heap[rootIndex] = orphan;
}

public static <T extends Comparable<? super T>> void heapsort(T[] array, int n) {
    for (int rootIndex = n / 2 - 1; rootIndex >= 0; rootIndex--) {

        reheap(array, rootIndex, n - 1);
        swap(array, 0, n - 1);

        for (int lastIndex = n - 2; lastIndex > 0; lastIndex--) {
            reheap(array, 0, lastIndex);
            swap(array, 0, lastIndex);

        }
    }
}

public static void swap(Object[] array, int i, int j) {
    Object temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

1 个答案:

答案 0 :(得分:1)

我不确定这是否是最佳解决方案,但您可以尝试将内部for-loop移出:

public static <T extends Comparable<? super T>> void heapsort(T[] array, int n) {
    for (int rootIndex = n / 2 - 1; rootIndex >= 0; rootIndex--) {
        reheap(array, rootIndex, n - 1);
        swap(array, 0, n - 1);
    }

    for (int lastIndex = n - 2; lastIndex > 0; lastIndex--) {
        reheap(array, 0, lastIndex);
        swap(array, 0, lastIndex);
    }
}