最小堆通过二叉树的数组表示;MoveDown函数无限循环
Minimum heap via array representation of a binary tree; MoveDown function loops infinitely
我正在使用数组数据结构实现最小堆,但是我的moveDown方法有问题(如果根节点的子节点都小于它,则在根节点将集合返回到堆)。我假设读者会知道最小堆是什么,但我将描述它,以防有人不知道或我的理解是错误的。
最小堆(在这种情况下)是一个二叉树,由这样的数组表示:
- 根节点是数据结构 中最小的值。
- 节点必须总是小于它的子节点
- 给定一个索引为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;
...
}
但是每当我说这种循环是个好主意时,我就会生气。上次有人说这"几乎是反模式",这是比较礼貌的回答之一。
相关文章:
- 表示"accepting anything for this template argument" C++概念的通配符
- 如何将ampl中的集合表示为c++中的向量
- std::is_base_of表示ctor编译错误
- 输入中的字符串数未知(以字母表示)
- 我可以信任表示整数的浮点或双精度来保持精度吗
- c++模板来表示多项式
- 询问在设计我的手臂模拟器功能表示格式1
- CMakeLists.txt中的命名空间表示法
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 如何计算Big-O表示法中的平均渐近运行时间
- 我应该如何表示我拥有的连续元素序列?
- 在C++中,使用带有 std::optional 参数的函数<T>来表示可选参数是否有意义?
- 在 std::无符号字符的向量处存储 int 的十六进制表示形式
- 表示类模板C++空类型
- 具有所表示类的相同构造函数签名的代理类模板
- 嵌套在循环中的两个循环的 big-O 表示法
- 具有引用成员的结构是否具有唯一的对象表示形式
- 使用 int 表示浮点除法 C++
- Geeksforgeeks C 程序故障排除:IEE 754 表示法为十进制
- 最小堆通过二叉树的数组表示;MoveDown函数无限循环