c - C 中的 Downheap 实现
问题描述
我有Downheap
C 语言的源代码,它将在不违反堆属性的情况下向下移动元素(每个节点的值大于/小于或等于其父节点的值,最小/最大值元素位于root.) 在树的任何节点上。
downheap(int k)
{
int temp, i;
temp = a[k];
while(k <= N/2)
{
i = 2*k;
if(i < N && a[i] < a[i+1]) i++;
if(temp > a[i]) break;
a[k] = a[i]; k = i;
}
a[k] = temp;
}
N
是数组的节点总数a
。我质疑这个程序是否可以从左到右下移节点以保持完全二叉树的属性?如何证明它,因为不存在右节点必须小于/大于左节点的属性。
解决方案
downheap(int k) // k is the index of the item in the heap
{
int temp, i;
temp = a[k]; // Use temp to store the item
while (k <= N / 2) // Make sure that we don't get outside of the heap boundaries
{
i = 2 * k; // Helper line to be used as an index for the children of the node
if (i < N && a[i] < a[i + 1]) i++; // check which of the children is
// Bigger to exchange with the item
if (temp > a[i]) break; // Item already in-place
a[k] = a[i];
k = i; // Exchange item with the children we found to be the biggest
}
a[k] = temp; // Put the item in its correct position
}
希望点赞有用
推荐阅读
- c++ - 在循环中重新声明 for 循环变量时出错
- python - 使用python将excel文件中的大量时间戳从一种格式转换为另一种格式
- macos - 替换所有匹配项而不更改文件结尾
- haskell - 在函数内部使用 haskell 类
- c# - 剃刀页面上的 Dropzone 返回 400 状态代码
- python - Python中的dde客户端连接?
- tableau-api - 如何根据分隔符在 Tableau 中查找文本的子字符串
- php - Laravel - 表单动作到控制器功能
- sql - 在sql中查找错误的重复数据
- c# - Unity3D:在运行时将球体对撞机添加到布料组件没有任何作用