二进制最小堆上的 BubbleDown 操作不起作用
我试图从二进制堆中提取最小值,但它不起作用。这是我的 BubbleDown 代码:
void heapBubbleDown(Heap * const heap, int idx) {
int min;
while(RIGHT(idx) < heap->count) {
min = LEFT(idx);
if(RIGHT(idx) < heap->count) {
if(heap->items[LEFT(idx)] > heap->items[RIGHT(idx)]) {
min = RIGHT(idx);
}
}
heapSwapValue(&(heap->items[idx]), &(heap->items[min]));
idx = min;
}
}
看起来它只交换了一些数字,但不是全部,我不明白为什么。我已经多次尝试以不同的方式重新编码......
我做错了什么?
I'm trying to extract the minimum from a binary heap but it's not working. Here's my BubbleDown code:
void heapBubbleDown(Heap * const heap, int idx) {
int min;
while(RIGHT(idx) < heap->count) {
min = LEFT(idx);
if(RIGHT(idx) < heap->count) {
if(heap->items[LEFT(idx)] > heap->items[RIGHT(idx)]) {
min = RIGHT(idx);
}
}
heapSwapValue(&(heap->items[idx]), &(heap->items[min]));
idx = min;
}
}
It looks like it only swaps a few numbers but not all of them, I can't understand why. I tried to recode it differently and many times already...
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为问题在于它交换了几个元素。当最小的子项 >= 当前项时,您必须停止。
我会将最后两行重写为:
I don't think the problem is that it swaps to few elements. You have to stop when the smallest child >= current item.
I would rewrite the last two lines to:
目前条件还不够。可能会出现没有右孩子但需要与左孩子进行交换的情况。此外,正如亨克建议的那样,您需要检查计算出的最小值实际上是否小于您当前的值。
The condition of the while is not sufficient. It may be the case that there is no right child but you need to do the swap with the left child. Moreover as Henk suggests, you need to check if the calculated minimum is in fact smaller than your current value.