这个重堆函数中的错误逻辑在哪里?

时间:2018-05-27 11:05:41

标签: 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 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);
    }
}
}

我的想法是,堆中的最低值总是在根中,这是我将在pop函数中加载(出列)的值。 但我有一些问题,它不会正确排序堆。 我的逻辑在这个函数中有什么问题,如果是的话,它在哪里?

1 个答案:

答案 0 :(得分:1)

构建堆只强制执行属性:

  • 如果是最小堆,则每个父级都小于子级
  • 如果是最大堆,则每个父级都大于其子级。
  • 如果最小 - 最大堆甚至深度级别(0,2,4 ..)较小,奇数级别(1,3,5 ......)大于其各自的子级。

但是堆不一定要排序。它将是平衡的,因为它按顺序逐级填充,从左到右。

Heapsort将使用堆函数对数组进行排序。最后一个数组也可以作为一个平衡和排序的堆。

相关问题