我尝试使用基于数组的堆实现优先级队列。到目前为止,我的堆类看起来像这样
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);
}
}
我的优先级队列看起来像这样
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();
}
}
但是,当我将一系列节点插入队列并使用我的print语句将它们吐出来时,它们的插入顺序与它们相同。我觉得我的trickleUp方法有问题,但无法弄清楚它是什么。
答案 0 :(得分:3)
数组中的数据不应该被排序。它是一堆。您必须连续删除一个元素并一次重新堆积一个元素以获得总排序。