0
우리는 수업 시간에 많은 정보를 얻었으며 교사는 우리에게 거의 가르쳐주지 못했습니다. 메모 (이 작업을 완료하기 위해 제공된 모든 것)에 따라 힙을 만들어야합니다. 그러나 내 문제는 힙에 데이터를 추가 할 방법이 없거나 주 데이터에 무엇이 들어갈 지 모른다는 것입니다. 전에 힙을 사용 해 본 적이 없으므로이 주제에 대해 아주 새로운 것입니다. 어떤 충고라도 감사 할 것입니다! 당신이 클래스 Heap
의 인스턴스를 만들 필요가 main()
에서힙과 인쇄에 추가
#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 2 3 4 5 6 7 힙 형태가 아님 – Josamoda
'swap'을 호출 할 때 실제 매개 변수 앞에 주소 연산자 (&)를 추가하면 프로그램 인쇄 : 7 5 6 4 2 1 3 이것은 최대 힙입니다. – jfly
[여기] (http://ideone.com/vSqCID)는 잘 동작하는 전체 코드입니다. – jfly