【问题标题】:Why doesn't my Max Heap Heapsort method work?为什么我的 Max Heap Heapsort 方法不起作用?
【发布时间】:2020-03-26 05:40:16
【问题描述】:

所以我正在使用 Max Heaps 的 java 实现。我的 Insert、bubbleUp 和 deleteMax(单独)方法似乎工作正常,但我的 heapsort 方法(调用 deleteMax)不能按预期工作(它不会导致错误消息;它只是不排序它们按应有的顺序排列)。我已经包含了下面的代码。非常感谢您对理解问题的任何帮助。谢谢!

整个课程可以在:https://repl.it/repls/FrequentPartialBlockchain

'''

    public int deleteMax(){
        if(this.numNodes == 0)
            throw new NoSuchElementException();
        else if(this.numNodes == 1){
            int elemToReturn = heapArr[0];
            heapArr[0] = null;
            return elemToReturn;
        }

        int elemToReturn = heapArr[0];
        heapArr[0] = heapArr[numNodes-1];
        heapArr[numNodes-1] = null;
        this.numNodes--;
        bubbleDown();
        return elemToReturn;
    }

    private void bubbleDown(){
        int n = 0;
        int L = 2 * n + 1; // L will hold the index of the left child
        while(L < this.numNodes - 1){
            int max = L;
            int R = L + 1; // R will hold the index of the right child

            if(R < this.numNodes - 1){
                if(heapArr[R] >= heapArr[L])
                    max++;
            }
            int temp;
            if(heapArr[n] < heapArr[max]){
                // swap
                temp = heapArr[n];
                heapArr[n] = heapArr[max];
                heapArr[max] = temp;

                n = max;
                L = 2 * n + 1;
            }
            else{
                break;
            }
        }
    }

    public static void heapsort(Integer[] arrayToSort){
        MaxHeap tempHeap = new MaxHeap(arrayToSort);
        for(int i = 0; i < tempHeap.numNodes; i++)
            arrayToSort[i] = (Integer) tempHeap.deleteMax();
    }

'''

【问题讨论】:

    标签: java sorting heap heapsort


    【解决方案1】:

    这个while 声明似乎是错误的:

    while(L < this.numNodes - 1){
    

    如果this.numNodes 是堆中的节点数,那么this.numNodes - 1 是最后一个节点。如果L 是堆中的最后一个节点,则此条件会阻止进入循环。

    在相关说明中,您在 deletMax 中的特殊情况已损坏。您删除了堆中唯一的节点,但忘记将 numNodes 设置为 0。

    【讨论】:

      猜你喜欢
      • 2019-05-23
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 2015-03-14
      • 2014-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多