二进制最小堆上的 BubbleDown 操作不起作用

发布于 2024-08-29 17:01:48 字数 570 浏览 5 评论 0原文

我试图从二进制堆中提取最小值,但它不起作用。这是我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悍妇囚夫 2024-09-05 17:01:48

我不认为问题在于它交换了几个元素。当最小的子项 >= 当前项时,您必须停止。

我会将最后两行重写为:

    if (heap->items[idx] > heap->items[min]) {
       heapSwapValue(&(heap->items[idx]), &(heap->items[min]));
       idx = min;
    } 
    else
       break;
}

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:

    if (heap->items[idx] > heap->items[min]) {
       heapSwapValue(&(heap->items[idx]), &(heap->items[min]));
       idx = min;
    } 
    else
       break;
}
孤君无依 2024-09-05 17:01:48

目前条件还不够。可能会出现没有右孩子但需要与左孩子进行交换的情况。此外,正如亨克建议的那样,您需要检查计算出的最小值实际上是否小于您当前的值。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文