0

I'm trying to implement a Priority Queue with an Array-Based heap. So far my heap class looks like this

public class ArrayHeap<E> 
{
    private Node<E>[] data; //Array to hold nodes
    private int capacity; //Length to make the array
    private int dataCount; //Current number of elements

    /**
     * Constructor for heap
     * @param passedCapacity
     */
    public ArrayHeap(int passedCapacity)
    {
        this.capacity = passedCapacity;
        this.dataCount = 0;
        data = new Node[capacity];
    }

    public void insert(Node<E> value) 
    {
        data[dataCount] = value;
        trickleUp(dataCount++);
    }    

    /**
     * Method to slide inserted data to correct position.
     * Based on Data Structures & Algorithms in Java, 2nd Edition (pg. 593)
     */
    private void trickleUp(int index)
    {
        int parent = index-1 / 2;
        Node<E> bottom = data[index];
        while(index > 0 && data[parent].getPriority() < bottom.getPriority())
        {
            data[index] = data[parent];
            index = parent;
            parent = (parent-1) / 2;
        }
        data[index] = bottom;
    }

    public E remove()
    {
        return null;
    }

    public void print()
    {
        for(int i = 0; i < dataCount; i++)
        {
            System.out.println(data[i].getPriority() + ": " + data[i].getData());
        }
        System.out.println("Total nodes: " + dataCount);
    }
}

and my priority queue looks like this

public class PriorityQueue<E> implements PriQue<E>
{
    private ArrayHeap<E> data;

    public PriorityQueue()
    {
        this.data = new ArrayHeap<E>(1000);
    }

    @Override
    public void insert(int pri, E dataToInsert) {
        Node<E> nodeToInsert = new Node<E>(pri, dataToInsert);
        data.insert(nodeToInsert);
    }

    public void print()
    {
        data.print();
    }
}

However, when I insert a series of Nodes into the queue and spit them back out with my print statement they just come out in the same order they were inserted. I feel like something is wrong with my trickleUp method but cannot figure out what it is.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Nick Gilbert
  • 4,159
  • 8
  • 43
  • 90
  • 1
    @EJP pointed out the main problem, but, in addition to that, `int parent = index-1 / 2;` in `trickleUp` is missing parentheses – Misha Apr 08 '15 at 23:21

1 Answers1

3

The data in the array isn't supposed to be sorted. It's a heap. You have to successively remove an element and re-heapify one at a time to get a total ordering.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
user207421
  • 305,947
  • 44
  • 307
  • 483