#include using namespace std;class A{ public: A(int *data, int len){} }; template class MaxHeap{ private: T *datas; int MaxSize; int currentSize; void KeepHeap(int root); bool del; public: MaxHeap(int MaxSize); MaxHeap(T *datas, int length); ~MaxHeap(); bool Insert(T data); T GetMax(); void RemoveMax(); void PrintHeap(){ for (int i=1; i<=currentSize; i++) { cout << datas[i] << " "; } cout << endl; } int GetCurrentSize() { return currentSize; } //void BuildMaxHeap(T *datas); }; template MaxHeap ::MaxHeap(T *datas, int length) { this->datas = datas; currentSize = length; MaxSize = currentSize; for (int i=currentSize/2; i>0; i--) { KeepHeap(i); } del = false; } template MaxHeap ::MaxHeap(int MaxSize) { this->MaxSize = MaxSize; datas = new T[this->MaxSize+1]; this->currentSize = 0; del = true; } template MaxHeap ::~MaxHeap() { if(del) delete []datas; } template bool MaxHeap ::Insert(T data) { if (currentSize+1 > MaxSize) { return false; } datas[++currentSize] = data; int index = currentSize; int temp = (index)/2; while (temp>=1) { if (datas[temp] T MaxHeap ::GetMax() { return datas[1]; } template void MaxHeap ::KeepHeap(int root) { int temp = datas[root]; while (root*2<=currentSize) { int child = root*2; if (child+1<=currentSize && datas[child] < datas[child+1]) { child++; } if (temp > datas[child]) { break; }else { datas[root] = datas[child]; } root = child; } datas[root] = temp; } template void MaxHeap ::RemoveMax() { int temp = datas[1]; datas[1] = datas[currentSize]; datas[currentSize] = temp; currentSize--; KeepHeap(1); } void MinK(int *data, int length, int k) { MaxHeap heap(length); for (int i=1; i heap.GetCurrentSize()) { heap.Insert(data[i]); }else{ if (data[i]
h(4); // h.Insert(1); // h.Insert(2); // h.Insert(3); int data[] = {-1,15,24,3,8,7,6,5,7}; int len = sizeof(data)/sizeof(int); MaxHeap
h(data, len-1); for (int i=1; i