next up previous index
Next: Strict Priority Queues Up: Binary Heaps and Priority Previous: Code for remove   Index


Implementation of Priority Queues

We have already specified the PriorityQueue interface in Figure 9.1. We now need to assemble the BinaryHeap implementation of this interface. The code is given in Figure 9.4.

Figure 9.4: A binary heap implementation of the PriorityQueue interface.
import java.util.NoSuchElementException;

public class BinaryHeap implements PriorityQueue {

    private Comparable[] heap;
    private int size;

    public BinaryHeap() {
        heap = new Comparable[1];
        size = 0;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public int size() {
        return size;
    }

    public void add(Comparable item) {
        if (size == heap.length) {
            Comparable[] newHeap = new Comparable[2 * heap.length];
            System.arraycopy(heap, 0, newHeap, 0, heap.length);
            heap = newHeap;
        }
        int parent, child = size++;
        while (child > 0 && heap[parent = (child - 1) / 2].compareTo(item) < 0) {
            heap[child] = heap[parent];
            child = parent;
        }
        heap[child] = item;
    }
  
    public Comparable remove() {
        if (size == 0) {
            throw new NoSuchElementException();
        }
        Comparable result = heap[0];
        Comparable item = heap[--size];
        int child, parent = 0; 
        while ((child = (2 * parent) + 1) < size) {
            if (child + 1 < size && heap[child].compareTo(heap[child + 1]) < 0) {
                ++child;
            }
            if (item.compareTo(heap[child]) < 0) {
                heap[parent] = heap[child];
                parent = child;
            } else {
                break;
            }
        }
        heap[parent] = item;
        return result;
    }

}

This makes use of a private heap array and a private variable size indicating the current number of items in the heap. The BinaryHeap constructor creates a new heap array of size 1 and initialises the heap as empty (size = 0). The isEmpty method is defined in the obvious way. The remove method is the same as before, except for using isEmpty() instead of (size == 0).

The add method is different in one respect. It now checks to see if there is room to hold another item in the current heap array. If not, the heap is doubled in size, with old items being copied to the new heap. This should be familiar from examples of the array implementation of stacks and ordinary queues.


next up previous index
Next: Strict Priority Queues Up: Binary Heaps and Priority Previous: Code for remove   Index
Peter Williams 2005-06-07