当前位置: 首页 > 知识库问答 >
问题:

对最大堆进行排序将返回按降序排序的列表。应该按升序排列吗?

窦伟
2023-03-14

我的教授介绍了如何使用ArrayList创建Max Heap类。然后他让我们写一个maxHeapSort方法。我几乎成功地将堆按降序排序,但我假设排序应该按升序。现在我使用一个最大堆为[11,5,8,3,4,1]的ArrayList,它排序为[11,8,5,3,4,1]。

这是我的maxHeapSort代码:

protected void maxHeapSort() {
    int n = this.heap.size();

    if(this.heap.size() == 0){
        return;
    }

    for(int i = n - 1; i > 0; i --){
        T temp = this.heap.get(0);
        this.heap.set(0, this.heap.get(i));
        this.heap.set(i, temp);

        this.heapifyDown(0);
    }
}

下面是我的教授给出的heapifyDown方法:

protected void heapifyDown(int index){
    // get the left and right children indices
    int leftIndex = 2 * index + 1;
    int rightIndex = 2 * index + 2;

    // set the max to the one that we are trying to heapify
    int maxIndex = index;

    // figure out which value is the max
    if(leftIndex < this.size && this.heap.get(leftIndex).compareTo(this.heap.get(maxIndex)) > 0){
        maxIndex = leftIndex;
    }

    if(rightIndex < this.size && this.heap.get(rightIndex).compareTo(this.heap.get(maxIndex)) > 0){
        maxIndex = rightIndex;
    }

    // do we need to swap and keep heapifying
    if (maxIndex != index) {
        // swap
        T temp = this.heap.get(index);
        this.heap.set(index, this.heap.get(maxIndex));
        this.heap.set(maxIndex, temp);

        // recurse
        this.heapifyDown(maxIndex);
    }

}

这是我的测试代码:

@Test
public void testMaxHeapSort(){
    MaxHeap<Integer> maxHeap = new MaxHeap<>();
    maxHeap.heap.add(11);
    maxHeap.heap.add(5);
    maxHeap.heap.add(8);
    maxHeap.heap.add(3);
    maxHeap.heap.add(4);
    maxHeap.heap.add(1);

    maxHeap.size = 6;

    maxHeap.maxHeapSort();

    assertEquals("[1, 3, 4, 5, 8, 11]", maxHeap.heap.toString());
}

共有1个答案

阎自怡
2023-03-14

只需更新比较,检查电流是否小于左侧,然后转到左侧,如果电流大于右侧,则转到右侧

    if(leftIndex < this.size && this.heap.get(maxIndex).compareTo(this.heap.get(leftIndex)) < 0) {
        maxIndex = leftIndex;
    }

    if(rightIndex < this.size && this.heap.get(maxIndex).compareTo(this.heap.get(rightIndex)) > 0){
        maxIndex = rightIndex;
    }
 类似资料:
  • 问题内容: 如何按降序对列表进行排序? 问题答案: 在一行中,使用: 将函数传递给:

  • 我注意到一件非常奇怪的事情。 读完这节课后,我在C中实现了一些堆排序代码。 代码如下。 奇怪的是,对我来说,构建min堆-提取min(或在构建min堆后在根目录下执行min-heapify)应该按升序进行。然而,在执行此代码并打印出结果向量后,我得到: 在试图弄清楚发生了什么的时候,我改变了 到 最终选择较大(或最大)的父节点和子节点,得到的向量为: 我是否做错了什么,或者我对堆/堆排序的理解不清

  • 我下面的代码不起作用,我也不知道为什么。 它编译得很好,但结果似乎没有排序。

  • 问题内容: 如何在如下所示的SQLAlchemy查询中使用ORDER BY ? 此查询有效,但以升序返回: 如果我尝试: 然后我得到:。 问题答案: 来自@ jpmc26的用法

  • 我有一个通用的链表,目前由int组成,我想在默认情况下按升序排序,然后切换一个布尔值,按降序排序。我该怎么做?