使用数组形成堆

时间:2011-10-16 12:00:40

标签: c++ heap heapsort

我正在尝试使用以下代码形成堆,但不确定为什么它没有显示正确的输出。

#include <iostream>

using namespace std;

int h[10], n;

void heapbottom()
{
    int i, j;
    for (i = n / 2; i >= 1; i--) {
        int k = i;
        int v = h[k];
        bool heap = false;
        while (!heap && 2 * k <= n) {
            cout << "\n i value is :" << i;
            j = 2 * k;
            if (j < n)          //there sre 2 children
            {
                if (h[j] < h[j + 1])
                    j++;
            }
            if (v >= h[j])
                heap = true;
            else {
                h[k] = h[j];
                k = j;
            }

            h[k] = v;
        }                       //end of while

    }
    cout << "\n HEAP GENERATED \n";
    for (int i = 0; i < n; i++)
        cout << "\n ELEMENT IS:" << h[i];
}

int main()
{

    cout << "\n Enter the maximum number of array elements \n";
    cin >> n;
    cout << "\n Enter the array to perform heap sort \n";
    for (int i = 0; i < n; i++)
        cin >> h[i];

    heapbottom();

    return 0;
}

1 个答案:

答案 0 :(得分:0)

如果我将外循环更改为

for (i = n / 2; i >= 0; i--)

我得到9 8 7 6 5 2,我相信这是一个有效的堆。