优先队列的堆实现?
Heap implementation of priority queue?
我正在尝试使用堆(根小于子级)实现患者队列,但是当我打印队列时,患者队列看起来没有优先级。
插入方法工作正常,但它是 enqueue
不优先项目?
// Heap class
.....some code
//insertion: inserts patients into minimum heap using an array.
//expand array as needed and reorder heap to maintain its properties
public void insert(ER_Patient patient) {
if(heapArray.length==count)
expand();
heapArray[count] = patient;
count++;
if(count>1)
reorder();
}
// Priority Queue class
.......some code
public void enqueue(ER_Patient patient) {
try {
heap.insert(patient);
} catch (NoSuchCategoryException exception) {
System.out.println("Can't enqueue");
}
}
// copy content of original's array to a new larger array
private void expand(){
ER_Patient[] tempArray = new ER_Patient[heapArray.length * 8];
for(int i=0;i<=heapArray.length-1;i++)
tempArray[i]=heapArray[i];
heapArray = tempArray;
}
// maintain heap property by keeping roots smaller than children
private void reorder(){
ER_Patient temp;
int next = count -1;
temp = heapArray[next];
while((next!=0) && temp.compareTo(heapArray[(next-1)/2])<0){
heapArray[next] = heapArray[(next-1)/2];
next = (next-1)/2;
}
heapArray[next] = temp;
}
reorder 方法的最后一行不应该是 while 循环的一部分吗?
heapArray[next] = temp;
此外,应该有适当的 dequeue() 方法
This is how I print:
public void display(Heap h)
{
for(int i=0;i<h.count;i++)
System.out.println(heapArray[i]);
}
错了。
除非您连续删除第一项并打印它,否则您将无法获得有序列表。堆数组本身不是顺序的。
我正在尝试使用堆(根小于子级)实现患者队列,但是当我打印队列时,患者队列看起来没有优先级。
插入方法工作正常,但它是 enqueue
不优先项目?
// Heap class
.....some code
//insertion: inserts patients into minimum heap using an array.
//expand array as needed and reorder heap to maintain its properties
public void insert(ER_Patient patient) {
if(heapArray.length==count)
expand();
heapArray[count] = patient;
count++;
if(count>1)
reorder();
}
// Priority Queue class
.......some code
public void enqueue(ER_Patient patient) {
try {
heap.insert(patient);
} catch (NoSuchCategoryException exception) {
System.out.println("Can't enqueue");
}
}
// copy content of original's array to a new larger array
private void expand(){
ER_Patient[] tempArray = new ER_Patient[heapArray.length * 8];
for(int i=0;i<=heapArray.length-1;i++)
tempArray[i]=heapArray[i];
heapArray = tempArray;
}
// maintain heap property by keeping roots smaller than children
private void reorder(){
ER_Patient temp;
int next = count -1;
temp = heapArray[next];
while((next!=0) && temp.compareTo(heapArray[(next-1)/2])<0){
heapArray[next] = heapArray[(next-1)/2];
next = (next-1)/2;
}
heapArray[next] = temp;
}
reorder 方法的最后一行不应该是 while 循环的一部分吗?
heapArray[next] = temp;
此外,应该有适当的 dequeue() 方法
This is how I print:
public void display(Heap h)
{
for(int i=0;i<h.count;i++)
System.out.println(heapArray[i]);
}
错了。
除非您连续删除第一项并打印它,否则您将无法获得有序列表。堆数组本身不是顺序的。