简体   繁体   English

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

[英]Why doesn't my Max Heap Heapsort method work?

So I'm working with the java implementation of Max Heaps.所以我正在使用 Max Heaps 的 java 实现。 My Insert, bubbleUp and deleteMax (on its own) methods seem to work fine, but my heapsort method (which calls deleteMax) doesn't work as its supposed to (it doesn't cause an error message; it just doesn't sort them in the order it's supposed to).我的 Insert、bubbleUp 和 deleteMax(单独的)方法似乎工作正常,但我的 heapsort 方法(调用 deleteMax)没有按预期工作(它不会导致错误消息;它只是不排序他们应该按照顺序)。 I've included the code below.我已经包含了下面的代码。 Any help understanding the problem is greatly appreciated.非常感谢任何帮助理解问题。 Thanks!谢谢!

The whole class can be found at: https://repl.it/repls/FrequentPartialBlockchain整个课程可以在以下位置找到: 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();
    }

''' '''

This while statement seems wrong:这个while语句似乎是错误的:

while(L < this.numNodes - 1){

If this.numNodes is the number of nodes in the heap, then this.numNodes - 1 is the last node.如果this.numNodes是堆中的节点数,则this.numNodes - 1是最后一个节点。 This condition, then, prevents the loop from being entered if L is the last node in the heap.如果L是堆中的最后一个节点,则此条件会阻止进入循环。

On a related note, your special case in deletMax is broken.在相关说明中,您在deletMax的特殊情况已损坏。 You remove the only node in the heap, but you forgot to set numNodes to 0.您删除了堆中唯一的节点,但您忘记将numNodes设置为 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM