Max Heap Heapsort方法为什么不起作用?

问题描述 投票:1回答:1

所以我正在使用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个回答
0
投票

while语句似乎是错误的:

while(L < this.numNodes - 1){

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

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

© www.soinside.com 2019 - 2024. All rights reserved.