修补一个数组

时间:2013-12-05 05:48:11

标签: c++

我目前正在编写一个小的堆码代码,重复运行时会向下冒泡,但每次看起来都没有发生任何事情。不知道这里有什么不对,也许我错过了什么?

template <class T>
void PriorityQueue<T>::heapify (int* arrs, int size){
    int i = (size-1)/2;
    while (i >= 0){
        bubbleDown(arrs, i, (size));
        i--;

    }
}

template <class T>
void PriorityQueue<T>::bubbleDown (int* arrs, int i, int size)
{
    //Each level node's are indexed at 2^(level) - 2 to 2^(level+2) - 2
    //Children of these node's levels are indexed at 2i+1 and 2i+2
    //The parent of node i, is indexed at (i-1)/2

    int leftChildren = (2*i)+1;
    int rightChildren = (2*i)+2;
    int largest = i;
    if (rightChildren < size)
    {
        if (arrs[leftChildren] < arrs[rightChildren]){
            largest = rightChildren;
        }
        else{
            largest = leftChildren;
        }
        if (arrs[i] > arrs[largest]){
            largest = i;    
        }
    }
    else if (leftChildren < size)
    {
        if (arrs[i] < arrs[leftChildren]){
            largest = leftChildren;
        }
    }
    if (arrs[i] < arrs[largest])
    {
        int temp = arrs[i];
        arrs[i] = arr[largest];
        arrs[largest] = temp;
    }

}

我这样称呼它:

PriorityQueue<int> test;
    int arr[] = {89, 29, 36, 48, 94, 13, 27, 70, 76, 37, 42, 58};
    test.heapify(arr, 12);
    for (int i = 0; i < 12; i++){
        cout << arr[i] << endl;
    }

控制台以与初始化数组相同的方式打印出它。

更新: 仍然得到奇怪的结果 [89,-842150451,36,29,94,0,27,70,48,37,42,13]

我应该得到的结果是 [94,76,89,70,48,58,13,27,36,29,37,42,23]

1 个答案:

答案 0 :(得分:0)

基本拼写错误。应该真的使用更有意义的名字