简体   繁体   English

堆执行优先队列?

[英]Heap implementation of priority queue?

I'm trying to implement a queue of patients using a heap (with root smaller than children) but when I print the queue, the queue of patients doesn't look prioritized. 我正在尝试使用堆(根小于孩子的根)来实现病人队列,但是当我打印队列时,病人队列看起来没有优先级。

Insertion method works fine but it's the enqueue that doesn't prioritize items? 插入方法可以很好地工作,但这是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;
}

This is how I print: 这是我的打印方式:

public void display(Heap h)
{
    for(int i=0;i<h.count;i++)
        System.out.println(heapArray[i]);
}

Wrong. 错误。

Unless you successively remove the first item and print it, you won't get an ordered listing. 除非您先删除第一项并打印,否则您将不会获得有序列表。 The heap array itself isn't sequential. 堆数组本身不是顺序的。

Shouldn't the last line of reorder method be part of the while loop? 重新排序方法的最后一行不应该是while循环的一部分吗?

heapArray[next] = temp;

Also, there should be proper dequeue() method out there 另外,应该有适当的dequeue()方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM