添加到堆和打印
Adding to heap and printing
我们在课堂上学到了很多东西,我的老师几乎没有教我们什么。根据注释(这是完成这项任务所需的全部内容),这应该会创建一个堆。然而,我的问题是,我看不到任何将数据添加到堆中的方法,也看不到主要内容。我以前从来没有用过堆,所以我对这个主题很陌生。任何建议都将不胜感激,谢谢!
#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]);
}
}
相关文章:
- Printf 命令不打印时添加了查找常见除数的新代码
- 如何在逗号后使用 cout 打印整数值,而无需在逗号后添加额外的零C++?
- oStream 不打印添加两个 valarray 的结果(使用运算符重载)
- C++ 添加编译器警告,以错误使用自定义打印/日志功能
- 如何在多维矢量中仅添加特定元素并将内容打印到屏幕
- 添加两个矩阵会打印一列垃圾数据 c++
- 为什么通过添加字符串文字和char初始化时,为什么不打印字符串
- 添加 g++ 的 -std= 标志时,C++打印到终端的速度要慢得多?
- 我在C++从函数中的用户获取输入、添加到数组和打印该数组时遇到问题
- 我如何对此代码进行添加以使用我的 arduino 打印一个完整的三角形
- 如何添加到此代码中,以便它打印"b"而不删除任何内容?
- 为什么RGB组件被打印为符号,直到我添加+'0'-'0'?
- 链表只打印添加新节点后的最后一个元素
- 无限循环heisenbug:如果我添加打印输出,它就会退出
- 如何打印添加功能的结果.
- 我在哪里可以找到在NS2库的cpp文件中生成的打印信息,其中我添加了一些cout()函数来打印一些信息
- C++打印矢量添加新行
- 使用Friend函数和operator+添加类变量并打印出来
- 哈希表添加和打印功能问题
- 链接列表的添加、删除和打印实现