Search code examples
javapriority-queuemin-heap

Implementing a priority queue with a min heap


I am attempting to implement a priority queue using a minheap, but my objects are coming out of the queue in the wrong order. My intuition tells me the issue is with my methods for sifting up or down in the queue, but I can't see where the issue is. Could someone look at my algorithms and see if there's anything wrong that is immediately apparent? Thank you in advance.

Here is the method for sifting down:

private void walkDown(int i) {

    if (outOfBounds(i))
    {
        throw new IndexOutOfBoundsException("Index not in heap : " + i);
    }

    int current = i;
    boolean right;
    Customer temp = this.heap[i];

    while (current < (this.size >>> 1)) 
    {

        right = false;

        if (right(current) < this.size && 
                 this.comparator.compare(this.heap[left(current)],
                        this.heap[right(current)]) > 0)
        {
            right = true;
        }


        if (this.comparator.compare(temp, right ? this.heap[right(current)] 
                : this.heap[left(current)]) < 0)
        {
            break;
        }

        current = right ? right(current) : left(current);
        this.heap[parent(current)] = this.heap[current];

    } 

    this.heap[current] = temp;

}

And the method for sifting up:

private void walkUp(int i) {

    if (outOfBounds(i))
    {
        throw new IndexOutOfBoundsException("Index not in heap : " + i);
    }

    int current = i;
    Customer temp = this.heap[i];

    while (current > 0) 
    {           
        if (this.comparator.compare(this.heap[current],
                    this.heap[parent(current)]) >= 0)
        {
            break;
        }

        this.heap[current] = this.heap[parent(current)];
        current = parent(current);

    }

    this.heap[current] = temp;

}

EDIT:

The compare method is defined as follows:

        @Override
        public int compare(Customer cust1, Customer cust2) {

            return cust1.priority() - cust2.priority();

        }

Solution

  • I ended up writing a method which executes the method above on every element in the heap, and that worked. It's not an elegant solution, but it gets the job done.