gpt4 book ai didi

java - Java实现优先级队列的问题

转载 作者:行者123 更新时间:2023-12-01 12:25:19 24 4
gpt4 key购买 nike

我目前的优先级队列存在问题。当我测试我的方法时,我收到一条错误消息,指出我的队列没有返回最高优先级。我已逐步完成,但我不明白为什么 Poll 或 Offer 方法会导致此问题。任何帮助,将不胜感激。谢谢

public class HeapArrayQueue <E extends Comparable<? super E> > extends AbstractQueue <E> { 

@SuppressWarnings("unchecked")
private E[] data = (E[])(new Comparable[7]);
private int count = 0;
private int front = 0;
public int size() {
return count;
}

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

public E poll() {
if (isEmpty())
return null;
else {
E ans = data[front ];
front = (front+1);
return ans;
}
}


public boolean offer(E element) {
if (element == null)return false;
else {
ensureCapacity();
data[count] = element;
bubbleUpFromIndex(count);
count++;
return true;
}
}

private void bubbleUpFromIndex(int nodeIndex) {
if (nodeIndex != 0){
int parent = (nodeIndex -1) / 2;
if (data[nodeIndex].compareTo(data[parent]) > 0){
swap(nodeIndex, parent);
bubbleUpFromIndex(parent);
}
}
}

private void swap(int from, int to) {
E temp = data[from];
data[from] = data[to];
data[to] = temp;
}

private void ensureCapacity() {
if (count == data.length) {
@SuppressWarnings("unchecked")
E[] newData = (E[])new Comparable[data.length * 2];

for (int loop = 0; loop < count; loop++) {
newData[loop] = data[loop];
}
data = newData;
}
return;
}

public Iterator<E> iterator() {
return null;
}
}

测试失败

@Test
public void QueueRespectsPriority() {
nonEmptyQueue.offer(t1);
assertEquals("Queue should return element with highest priority", t1, nonEmptyQueue.poll());
}

最佳答案

我在 vic 做 comp103 吗?看起来与我现在正在做的事情非常相似。

我看到的第一件事是您没有在民意调查中保留正确的优先级。这里(伪代码是我的方法)

public E poll(){
if (count = 0) return null
E item = root // We are returning the root node so store it as a var
root = end // place the end item in root position
end = null // set end item to null
count-- // subtract count
sinkDown(0) // Call sink down to restore ordering
return item // return item
}

关于java - Java实现优先级队列的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26398209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com