java 有堆数据结构吗_java – 堆数据结构重堆方法

我正在完成我的任务,即从文本文件中读取,将前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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值