堆排序不按预期工作

时间:2014-12-30 00:44:49

标签: algorithm sorting

我正在尝试使用CLRS书籍实现堆排序。我的代码是:

private void maxHeapify(int[] input, int i) {
    int l = left(i);
    int r = right(i);
    int largest;

    if(l <= heapSize && input[l] > input[i]) {
        largest = l;
    } else {
        largest = i;
    }

    if(r <= heapSize && input[r] > input[largest]) {
        largest = r;
    }

    if(largest != i) {
        swap(input, i, largest);
        maxHeapify(input, largest);
    }
}

private void buildMaxHeap(int[] input) {
    heapSize = input.length;
    for(int i = (input.length-1)/2; i >= 0; i--) {
        maxHeapify(input, i);
    }
}

public void heapSort(int[] input) {
    buildMaxHeap(input);

    for(int i = input.length-1; i > 0; i--) {
        swap(input, 0, i);
        heapSize--;
        maxHeapify(input, 0);
    }
}

对于{1, 5, 3, 7, 2, 0, 6, 2}的输入,我的答案为7 3 0 6 2 5 1 2。为什么会这样?我猜这与行for(int i = (input.length-1)/2; i >= 0; i--)有关,但我不能指责它。

0 个答案:

没有答案
相关问题