添加到堆和打印

Adding to heap and printing

本文关键字:打印 添加      更新时间:2023-10-16

我们在课堂上学到了很多东西,我的老师几乎没有教我们什么。根据注释(这是完成这项任务所需的全部内容),这应该会创建一个堆。然而,我的问题是,我看不到任何将数据添加到堆中的方法,也看不到主要内容。我以前从来没有用过堆,所以我对这个主题很陌生。任何建议都将不胜感激,谢谢!

 #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()
{

}

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

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]);
    }
}