0
我遇到问题的方法是popTop 我有一个OurProcess数组,它有一个变量名currentPriority,我将这个堆从 最小的排序到最大但popTop只是发回第一个对象,然后离开优先级[0] == null,我似乎无法弄清楚。任何帮助将不胜感激!在java中弹出并重新排序堆对象的元素
public class Queue {
int number1 = 0;
final int root = 0; // an easy reference to the root of the heap
int endPoint = 0; // Endpoint is where the first blank space in in queue is
int size; // an easier value to work with than the length of the array
OurProcess[] priorities; // The array that the whole class is built upon
char location; // This is just shorthand for the name of the object
Queue(int size, char location) {
this.location = location;
this.size = size;
priorities = new OurProcess[size];
}
Queue(OurProcess[] processesArray, char location) throws Exception {
this.location = location;
size = processesArray.length;
priorities = new OurProcess[processesArray.length];
for (int i = 0; i < processesArray.length - 1; i++) {
insert(processesArray[i]);
}
}
public void insert(OurProcess toAdd) {
if (endPoint == priorities.length) {
System.out.println("Out of bounds");
} else {
endPoint++;
priorities[endPoint - 1] = toAdd;
siftUp(endPoint - 1);
}
}
public void siftUp(int nodeIndex) {
int parentIndex;
OurProcess tmp;
if (nodeIndex < priorities.length) {
parentIndex = (nodeIndex - 1)/2;
while (priorities[parentIndex].currentPriority > priorities[nodeIndex].currentPriority) {
tmp = priorities[parentIndex];
priorities[parentIndex] = priorities[nodeIndex];
priorities[nodeIndex] = tmp;
siftUp(parentIndex);
}
}
}
public OurProcess popTop() {
OurProcess pop = priorities[root]; // Copy the root of our array
priorities[root] = priorities[endPoint]; // Place our object at the end
priorities[endPoint] = null;
int index = root;
int leftChild = index*2+1;
int rightChild, lesserChild;
while(index < priorities.length && priorities[index] != null){
lesserChild = leftChild;
rightChild = leftChild + 1;
if (priorities[rightChild].currentPriority < priorities[leftChild].currentPriority){
lesserChild = rightChild;
}
if (priorities[lesserChild].currentPriority < priorities[index].currentPriority){
OurProcess temp = priorities[lesserChild];
priorities[lesserChild] = priorities[index];
priorities[index] = temp;
index = lesserChild;
leftChild = index*2+1;
}
}
return pop; // Return the top of the array
}
}
你确定你需要一个自定义算法/数据结构吗? – 2014-11-23 19:20:42