堆實例

#include <iostream>
using namespace std; class A { public: A(int *data, int len){} }; template<class T> 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 <class T> MaxHeap<T>::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<class T> MaxHeap<T>::MaxHeap(int MaxSize) { this->MaxSize = MaxSize; datas = new T[this->MaxSize+1]; this->currentSize = 0; del = true; } template<class T> MaxHeap<T>::~MaxHeap() { if(del) delete []datas; } template<class T> bool  MaxHeap<T>::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]<data) { datas[index] = datas[temp]; index = temp; temp = temp/2; }else{ break; } } datas[index] = data; return true; } template<class T> T MaxHeap<T>::GetMax() { return datas[1]; } template<class T> void MaxHeap<T>::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<class T> void MaxHeap<T>::RemoveMax() { int temp = datas[1]; datas[1] = datas[currentSize]; datas[currentSize] = temp; currentSize--; KeepHeap(1); } void MinK(int *data, int length, int k) { MaxHeap<int> heap(length); for (int i=1; i<length; i++) { if (k>heap.GetCurrentSize()) { heap.Insert(data[i]); }else{ if (data[i]<heap.GetMax()) { heap.RemoveMax(); heap.Insert(data[i]); } } } heap.PrintHeap(); } int main(int argc, char* argv[]) { // MaxHeap<int> 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<int> h(data, len-1); for (int i=1; i<len; i++) { h.RemoveMax(); } for (i=1; i<len; i++) cout << data[i] << " "; cout << endl; MinK(data,len,3); return 0; }
相關文章
相關標籤/搜索