#pragma once
#include <iostream>
using namespace std;
template <class Type>
class HeapList
{
private:
Type* entry;
int count;
public:
HeapList();
HeapList(int n);
HeapList(Type arr[],int n);
~HeapList(){
if(count > 0)
delete []entry;
};
void buildHeap();
void adjustHeap(const Type ¤t,int low, int high);
void heapSort();
//friend ostream& operator<<(ostream &os, const HeapList<Type> &hlist);
void printAll();
};
template <class Type>
HeapList<Type>::HeapList()
{
count = 0;
entry = NULL;
}
template <class Type>
HeapList<Type>::HeapList(int n)
{
count = n;
entry = new Type[count];
for(int i = 0; i < count; i++)
{
entry[i] = 0; //是否需要给初值?潜在bug。与Type实例有关
}
}
template <class Type>
HeapList<Type>::HeapList(Type arr[], int n)
{
count = n;
entry = new Type[count];
for(int i = 0; i < count; i++)
{
entry[i] = arr[i];
}
}
template <class Type>
void HeapList<Type>::adjustHeap(const Type ¤t, int low, int high)
{
int large;//保存较大孩子的位置
large = low*2+1; //成为low的左孩子
while(large <= high)
{
if(large < high && entry[large] < entry[large+1])
large++;
if(current >= entry[large])//又一潜在bug,是否重载〉=
break;
else
{
entry[low] = entry[large];
low = large;//降为左或右子树
large = low*2+1;
}
}
entry[low] = current;//把最初需要调整的数字放在正确的位置
}
//建堆算法:所有叶子节点都符合堆的定义,故从第一个非叶子节点开始
//用上述算法把该子树调整为堆,直至整个完全二叉树调整成为初始堆
template <class Type>
void HeapList<Type>::buildHeap()
{
int low;
for(low = count/2-1; low >= 0; low--)
{
Type current = entry[low];
adjustHeap(current, low, count-1);
}
}
template <class Type>
void HeapList<Type>::heapSort()
{
Type current;
int last_unsorted;
buildHeap();
for(last_unsorted = count -1; last_unsorted > 0; last_unsorted--)
{
current = entry[last_unsorted];
entry[last_unsorted] = entry[0];
adjustHeap(current, 0, last_unsorted-1);
}
}
template <class Type>
void HeapList<Type>::printAll()
{
for(int i = 0; i < count; i++)
cout<<entry[i]<<endl;
}
/*template <class Type>
ostream& operator << (ostream &os, const HeapList<Type> &hlist)
{
for(int i = 0; i < hlist.count; i++)
os<<hlist.entry[i]<<endl;
return os;
}*/
//cpp
#include "heaph.h"
int main()
{
int arr[5] = {5,1,3,4,2};
HeapList<int>* hlist = new HeapList<int>(arr, 5);
hlist->heapSort();
//for(int i = 0; i < 5; i++)
// cout << hlist->entry[i] << endl;
//cout << *hlist;
hlist->printAll();
delete hlist;
return 0;
}