gpt4 book ai didi

java - 优先级队列不按优先级插入东西

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

我正在尝试使用基于数组的堆实现优先级队列。到目前为止我的堆类看起来像这样

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 方法有问题,但无法弄清楚它是什么。

最佳答案

数组中的数据不应排序。这是一堆。您必须连续删除一个元素并一次重新堆化一个元素才能获得总排序。

关于java - 优先级队列不按优先级插入东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29526877/

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