最小堆通过二叉树的数组表示;MoveDown函数无限循环

Minimum heap via array representation of a binary tree; MoveDown function loops infinitely

本文关键字:表示 MoveDown 函数 无限循环 数组 二叉树      更新时间:2023-10-16

我正在使用数组数据结构实现最小堆,但是我的moveDown方法有问题(如果根节点的子节点都小于它,则在根节点将集合返回到堆)。我假设读者会知道最小堆是什么,但我将描述它,以防有人不知道或我的理解是错误的。

最小堆(在这种情况下)是一个二叉树,由这样的数组表示:

  1. 根节点是数据结构
  2. 中最小的值。
  3. 节点必须总是小于它的子节点
  4. 给定一个索引为I的数组节点,它的左子节点索引为I*2 + 1右子节点索引为I*2 + 2

我目前的问题是,我的moveDown函数运行到一个无限循环时,交换。我很难找到一个逻辑错误,所以我担心它可能是更接近词根的东西(双关语,我忍不住)。

heap.cpp文件中值得注意的数据成员:

int size;
MiniVector array;// The implementing custom array
void moveDown(int root);

在heap.cpp文件中的moveDown函数:

void BinaryHeap::moveDown( int root ){
    int temp = root;
    int tempLC = temp*2 + 1;//LeftChild
    int tempRC = temp*2 + 2;//RightChild
    //Not a leaf
    while( ( tempLC < array.size() && tempRC < array.size() )
        &&
    ( (array[temp] > array[tempLC]) || (array[temp] > array[tempRC]) ) ){
        int hold = array[temp];
        if( array[temp] > array[tempRC] ){
            array[temp] = array[tempRC];
            array[tempRC] = hold;
            temp = tempRC;
        }
        else{
            array[temp] = array[tempLC];
            array[tempLC] = hold;
            temp = tempLC;
        }
        int tempLC = temp*2 + 1;//LeftChild
        int tempRC = temp*2 + 2;//RightChild
    }
}

重新声明变量。在while循环的底部

    int tempLC = temp*2 + 1;//LeftChild
    int tempRC = temp*2 + 2;//RightChild
应该

    tempLC = temp*2 + 1;//LeftChild
    tempRC = temp*2 + 2;//RightChild

在Java中不会发生。

也不会发生,如果你把你的循环重写为一个无限的for循环,中间有一个断点

for (;;)
{
    int tempLC = temp*2 + 1;//LeftChild
    int tempRC = temp*2 + 2;//RightChild
    if (...)
        break;
    ...
}

但是每当我说这种循环是个好主意时,我就会生气。上次有人说这"几乎是反模式",这是比较礼貌的回答之一。