添加到堆和打印

时间:2014-04-15 02:09:26

标签: c++ algorithm data-structures heap

我们一直在课堂上学习堆,而我的老师几乎没有教过我们什么。根据笔记(这是完成此任务所给出的所有内容),这应该创建一个堆。然而,我的问题是我没有看到任何方法将数据添加到堆或主要内容。我之前从未使用过堆,所以我对这个主题很新。任何建议都将不胜感激,谢谢!

 #include <iostream>

using namespace std;

template<class ItemType>
class Heap{
   public:
    void ReheapDown(int root,int bottom);
    void ReheapUp(int root, int bottom);
    void swap(ItemType * a, ItemType * b);

    ItemType * elements;
    int numEle;

};
template<class ItemType>
void Heap<ItemType>::swap(ItemType *a, ItemType *b)
{
    ItemType x;
    x = *a;
    *a = *b;
    *b = x;
}

template<class ItemType>
void Heap<ItemType>::ReheapDown(int root, int bottom)
{
    int maxChild;
    int rightChild;
    int leftChild;

    leftChild = root*2 + 1;
    rightChild = root*2 +2;

    if(leftChild <= bottom)
    {
        if(leftChild == bottom)
            maxChild = leftChild;
        else
        {
            if(elements[leftChild] <= elements[rightChild])
                maxChild = rightChild;
            else
                maxChild = leftChild;
        }
        if(elements[root] < elements[maxChild])
        {
            swap(elements[root],elements[maxChild]);
            ReheapDown(maxChild,bottom);
        }
    }
}


template<class ItemType>
void Heap<ItemType>::ReheapUp(int root, int bottom)
{
    int parent;
    if(bottom > root)
    {
        parent = (bottom -1) / 2;
        if(elements[parent] < elements[bottom])
        {
            swap(elements[parent],elements[bottom]);
            ReheapUp(root,parent);
        }
    }
}


int main()
{


}

1 个答案:

答案 0 :(得分:0)

main()中,您需要创建类Heap的实例,然后设置其数据成员的值,并通过调用其成员函数来构建堆:
顺便说一下,在调用swap时代码中存在问题,您应该在实际参数之前添加地址运算符(&amp;)。

int main()
{
    Heap<int> heap;
    int array[] = {1,2,3,4,5,6,7};
    heap.elements = array;
    heap.numEle = sizeof array / sizeof(int);

    int start;
    for (start = (heap.numEle-2)/2; start >=0; start--) {
        heap.ReheapDown(start, heap.numEle - 1); // this is the Button-Up version of heapify
    }

    for(int i = 0; i < heap.numEle; ++i)
    {
        printf("%d ", heap.elements[i]);
    }

    // test the Top-down version of heapify.
    heap.elements = array;

    int end;
    for(end = 1; end < heap.numEle; ++end)
        heap.ReheapUp(0, end); // this is the Top-down version of heapify

    printf("\n");
    for(int i = 0; i < heap.numEle; ++i)
    {
        printf("%d ", heap.elements[i]);
    }
}