C++ 此重新堆函数中的错误逻辑在哪里?

C++ 此重新堆函数中的错误逻辑在哪里?,c++,heap,deque,C++,Heap,Deque,我目前正在使用一个堆结构,该结构被假定用于对数组中的数字进行排序。当我想在从堆中弹出(出列)一个元素时对结构进行排序时,我在代码中做了类似的事情 template<typename T> inline void dHeap<T>::reHeapDown(int root, int bottom) { int minChild; int rightChild; int leftChild; int temp; // Get index

我目前正在使用一个堆结构,该结构被假定用于对数组中的数字进行排序。当我想在从堆中弹出(出列)一个元素时对结构进行排序时,我在代码中做了类似的事情

template<typename T>
inline void dHeap<T>::reHeapDown(int root, int bottom)
{
    int minChild;
    int rightChild;
    int leftChild;
    int temp;



// Get index of root's right/left child
leftChild = root * 2 + 1;
rightChild = root * 2 + 2;

//Then we are not done with re-heaping
if (leftChild <= bottom)
{
    if (leftChild == bottom)
    {
        minChild = leftChild;
    }

    else
    {
        if (arr[leftChild] <= arr[rightChild])
            minChild = leftChild;
        else
            minChild = rightChild;
    }

    if (arr[root] > arr[minChild])
    {
        // Swap these two elements
        temp = arr[root];
        arr[root] = arr[minChild];
        arr[minChild] = temp;
        // Make recursive call till reheaping completed
        reHeapDown(minChild, bottom);
    }
}
}
模板
内联void dHeap::reHeapDown(int root,int bottom)
{
int minChild;
int rightChild;
int-leftChild;
内部温度;
//获取根目录的右/左子目录的索引
leftChild=根*2+1;
rightChild=根*2+2;
//那么我们还没有完成重新堆积

如果(leftChild构建堆仅强制该属性:

  • 在最小堆的情况下,每个父级都小于它的子级
  • 在最大堆的情况下,每个父级都大于其子级
  • 在最小-最大堆的情况下,偶数深度级别(0,2,4…)较小,奇数级别(1,3,5…)大于各自的子级
然而,堆不一定会被排序,它会被平衡,因为它是按从左到右的顺序逐级填充的


将使用堆函数对数组进行排序。最终的数组也将用作平衡和排序的堆。

是否尝试使用调试器单步执行代码?您的代码是正确的。不能保证最小堆是平衡或排序的。您可以假定根元素是最小的,并且每个父元素都小于其子元素。如果y如果你想对它进行排序,你需要实现一种对它进行排序的方法…@attersson啊哈,好吧!我不知道实际上,二进制堆也能保证shape属性:每个级别,可能除了最后一个级别外,都已满满。如果最后一个级别未满,则从左侧填充。因此,这是一个平衡树。