我正在处理我的作业,即从文本文件中读取,将前10个单词存储在堆中。然后继续从文本文件中读取,如果单词小于堆的根,则替换它并重新堆叠整个堆。我的代码似乎在大多数情况下工作,但我遇到了一些问题。
我最终会得到一个包含单词abandoning abandons
abased
abash
abashed
abashes
abasing
abate
abatement
abbe
但是我得到了abashes
abashed abash
abased abandons abandoning bewilderedly
abandoning armful abandoning
到目前为止,这是我的代码:
public static void readFile() {
BufferedReader reader;
String inputLine;
int counter = 0;
try {
reader = new BufferedReader(new FileReader(".\\src\\dictionary.txt"));
while((inputLine = reader.readLine()) != null) {
if(counter < 10) {
heap.insert(inputLine);
counter++;
}
if(inputLine.compareTo(heap.find(0)) < 0) {
heap.change(0, inputLine);
}
}
} catch (IOException e) {
System.out.println("Error: " + e);
}
}
public boolean insert(String value) {
if(currentSize == maxSize) { return false; }
Node newNode = new Node(value);
heap[currentSize] = newNode;
trickleUp(currentSize++);
return true;
}
public void trickleUp(int index) {
int parent = (index - 1) / 2;
Node bottom = heap[index];
while(index > 0 && heap[parent].getData().compareTo(bottom.getData()) < 0) {
heap[index] = heap[parent];
index = parent;
parent = (parent - 1) / 2;
}
heap[index] = bottom;
}
public void trickleDown(int index) {
int largerChild;
Node top = heap[index];
while(index < currentSize / 2) {
int leftChild = 2 * index + 1;
int rightChild = index + 1;
if(rightChild < currentSize && heap[leftChild].getData().compareTo(heap[rightChild].getData()) < 0) {
largerChild = rightChild;
} else {
largerChild = leftChild;
}
if(top.getData().compareTo(heap[largerChild].getData()) > 0) {
break;
}
heap[index] = heap[largerChild];
index = largerChild;
}
heap[index] = top;
}
public boolean change(int index, String newValue) {
if(index < 0 || index >= currentSize) { return false; }
String oldValue = heap[index].getData();
heap[index].setData(newValue);
if(oldValue.compareTo(newValue) < 0) {
trickleUp(index);
} else {
trickleDown(index);
}
return true;
}
答案 0 :(得分:2)
如果您使用这样的索引,则不会获得二叉树:
int leftChild = 2 * index + 1;
int rightChild = index + 1;
我认为你打算写这个:
int leftChild = 2 * index + 1;
int rightChild = 2 * index + 2;
所以树看起来像这样
0
/ \
1 2
/ \ / \
3 4 5 6
/ \
7 8 ... and so on
至于重复元素,据我所知,堆可以包含重复项,并且不支持重复删除。例如,这是一个有效的数字堆
10
/ \
9 8
/ \ / \
5 7 7 6