简体   繁体   中英

Debugging Max Heap in Java

Awhile back I was programming in C++ and I found a tutorial on making a max heap. This was the code and it seems to produce a correctly order heap.`

#include <iostream>

const int size = 14;
static int A[size] = {1, 2, 5, 10, 2, 11, 12, 7, 23, 22, 34, 54, 12, 22};

int left(int i)
{
    return (2*i)+1;
}

int right(int i)
{
    return (2*i)+2;
}

//a leaf of a value less than the size of the array
//and larger than the center of the array
bool isLeaf(int i)
{
    if(i >= (size/2) && i <= size)
    {
        return true;
    }
    return false;
}

void maxHeapify(int i)
{
    //if it isn't a leaf it may need to be swapped
    if(!isLeaf(i))
    {
        //if the value is less than it's right or left child
        if(A[i] < A[left(i)] || A[i] < A[right(i)])
        {
            //if the left child is smaller
            if(A[left(i)] > A[right(i)])
            {
                //swap the left child with the index
                std::cout << "Swapping " << A[i] << " and " << A[left(i)] << std::endl;
                int a = A[i];
                A[i] = A[left(i)];
                A[left(i)] = a;
                //and run maxHeapify in it. This will push the value to
                //it's lowest point and order all things below the parent
                maxHeapify(left(i));
            }
            else
            {
                //else swap with the right child since it is larger
                std::cout << "Swapping " << A[i] << " and " << A[right(i)] << std::endl;
                int a = A[i];
                A[i] = A[right(i)];
                A[right(i)] = a;
                //run maxheap on that value. This will push the value to it's lowest position
                maxHeapify(right(i));
            }
        }
    }
}


bool buildHeap()
{
    //need to run for each node that is not a leaf
    for(int i = (size/2); i >= 0; i--)
    {
        maxHeapify(i);
    }
    return true;
}


int main()
{
    std::cout << "before: " << std::endl;
    for(int i = 0; i < size; i++)
    {
        std::cout << A[i] << ", ";
    }
    std::cout << std::endl;
    buildHeap();
    std::cout << "After: " << std::endl;
    for(int i = 0; i < size; i++)
    {
        std::cout << A[i] << ",";
    }
    std::cout << std::endl;
    return 0;
}

The output of the above is:
Before:
1, 2, 5, 10, 2, 11, 12, 7, 23, 22, 34, 54, 12, 22,
Swapping 12 and 22
Swapping 11 and 54
Swapping 2 and 34
Swapping 10 and 23
Swapping 5 and 54
Swapping 5 and 12
Swapping 2 and 34
Swapping 2 and 22
Swapping 1 and 54
Swapping 1 and 22
Swapping 1 and 12

After:
54,34,22,23,22,12,12,7,10,2,2,11,5,1,

Currently I am studying for a midterm and I am trying to reproduce my code in java. I have been looking at this for awhile and I can't seem to find where I am going wrong. Here is the broken java: Main.java

public class Main {

    /**
     * @param args
     */
    public static void main(String[] args) {
        int[] a = { 1, 2, 5, 10, 2, 11, 12, 7, 23, 22, 34, 54, 12, 22 };
        System.out.println("Begfore");
        for (int i = 0; i < a.length; i++) {
            System.out.print(a[i] + ", ");
        }
        Heap h = new Heap(a);
        h.buildHeap();
        h.print();
        System.out.println();
        System.out.println(a.length);
    }
}

Heap.java

public class Heap {

    int[] heap;

    public Heap(int[] a) {
        // heap = new int[a.length];
        heap = a;
    }

    public void buildHeap() {
        for (int i = heap.length / 2; i >= 0; i--) {
            maxHeapify(i);
        }
    }

    public int getLeft(int a) {
        return (2 * a) + 1;
    }

    public int getRight(int a) {
        return (2 * a) + 2;
    }

    private boolean isLeaf(int a) {
        if (a >= ((heap.length) / 2) && a <= heap.length) {
            return true;
        } else {
            return false;
        }
    }

    public void maxHeapify(int a) {
        if (!isLeaf(a)) {
            if (heap[a] < heap[getLeft(a)] || heap[a] < heap[getRight(a)]) {
                if (getLeft(a) <= heap.length && getRight(a) < heap.length) {
                    if (heap[getLeft(a)] > heap[getRight(a)]) {
                        int watcher = heap[a];
                        heap[a] = heap[getLeft(a)];
                        heap[getLeft(a)] = watcher;
                        maxHeapify(getLeft(a));
                    } else {
                        int watcher = heap[a];
                        heap[a] = heap[getRight(a)];
                        heap[getRight(a)] = watcher;
                        maxHeapify(getRight(a));
                    }
                }
            }
        }
    }

    public void print() {
        System.out.println("heap");
        for (int i = 0; i < heap.length; i++) {
            System.out.print(heap[i] + ", ");
        }
    }
}

Which doesn't produce a correct max ordered heap.
Java output: 54, 34, 12, 23, 22, 12, 1, 7, 10, 2, 2, 11, 5, 22,

This code has some Basic problems. Let me explain them.

First of all in Max Heapify function, you do not need to check for the condition that whether it is a leaf or not. This brings me to your max heapify function call.

The heapify function is always called from indices heap.length/2 - 1 to 0 , notice that you have not used the -1. This allows the heapify to always be saved from the leaves because in a binary heap whether max on min, the leaves are placed at indices heap.length/2 to heap.length-1.

Another mistake with this code is with the way indices are used. There are 2 ways to use indices.

Either use real indices from 0 to heap.length -1 in this case there should not be any condition such as

<=heap.length or >=heap.length

But you have used conditions like this in you heapify code.

Or use fake indices which range from 1 to heap.length and whenever you use them inside [ ] just subtract -1. This works perfectly in my java code.

Hope this helps. I can give you the java code if you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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