简体   繁体   中英

MaxHeap implementation in Java doesn't work properly

I implemented Heap by extending ArrayList. However, it seems to work well as minheap (with little difference to this code), but it does not work properly as maxheap. I think I have a part or a part that I am using wrongly. I wonder what is wrong or misunderstood.

And if there is a better way, I would really appreciate it if you comment it, thanks.

class Heap<T extends Comparable<T>> extends ArrayList<T>   {

    public void insert(T elem) {
        this.add(elem);
        int idx = this.size() - 1;
        if(idx > 0 && this.compare(idx, (idx - 1) / 2)){
            Collections.swap(this, idx, (idx - 1) / 2);
            idx = (idx - 1) / 2;
        }
    }
    public void removeTop() {
        if(this.size() == 1) {
            this.remove(0);
            return;
        }
        this.set(0, this.remove(this.size() - 1));
        int here = 0;
        while(true) {
            int left = here * 2 + 1;
            int right = here * 2 + 2;
            if(left >= this.size()) break;
            int next = here;
            if(!this.compare(next, left)) {
                next = left;
            }
            if(right < this.size() && !this.compare(next, right)){
                next = right;
            }
            if(next == here) break;
            Collections.swap(this, next, here);
            here = next;
        }
    }

    private void swap(int idx1, int idx2) {
        T temp = this.get(idx1);
        this.set(idx1, this.get(idx2));
        this.set(idx2, temp);
    }

    private boolean compare(int idx1, int idx2) {
        return this.get(idx1).compareTo(this.get(idx2)) >= 0;
    }
}

(+) The method compare is for comparing two elements depending on the type. I would like to get a kind of Compare function at the time of initialization of heap. like...

Heap<Integer> heap = new Heap<Integer>(new SomekindofCompareFunction());

is it possible in Java?

Use a Comparator :

class Heap<T> extends ArrayList<T>   {
    private final Comparator<T> comparator;

    public Heap(Comparator<T> comparator) {
        this.comparator = comparator;
    }

...

    private boolean compare(int idx1, int idx2) {
        return comparator.compare(get(idx1), get(idx2)) >= 0;
    }
}

You would create the Heap like this:

    Heap<Integer> heap = new Heap<Integer>((a,b) -> a.compareTo(b));

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