我正在完成我的任务,即从文本文件中读取,将前10个单词存储在堆中.然后继续从文本文件中读取,如果单词小于堆的根,则替换它并重新堆叠整个堆.我的代码似乎在大多数情况下工作,但我遇到了一些问题.
>有些单词即使它们小于根也没有被交换
>重复的单词
我应该最终得到一个包含放弃放弃的词的堆
自卑
惑
愧
abashes
abasing
杀
减排
阿贝
但是,我得到的话,abashes
羞涩的ab ..
贬低放弃放弃了困惑
放弃武装放弃
到目前为止,这是我的代码:
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;
}
最佳答案 如果使用这样的索引,则不会获得二叉树:
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