ArrayHeap类不返回已排序的数组

时间:2014-11-19 20:53:05

标签: java arrays heap

我正在使用java。

以下是我班级的代码:

/**
 * Ensure that the ordering property of the heap holds after
 * the insertion of an new element into the heap.
 */
private void interchangeUp() {
    int current = size - 1;
    int parent = (current - 1) / 2;

    while(parent <= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
        swap(parent, current);
        current = parent;
        parent = (current - 1) / 2;
    }
}

我查看了我的代码,似乎无法弄清楚导致此问题的原因。

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

你在算法中有一个小错误:

private void interchangeUp() {
    int current = size - 1;
    int parent = (current - 1) / 2;

    //while (parent <= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
    while (parent >= 0 && heapForm[current].compareTo(heapForm[parent]) < 0) {
        swap(parent, current);
        current = parent;
        parent = (current - 1) / 2;
    }
}