[Data Structure] Pile-based priority queue

#include #include #include#include using namespace std ;templatestruct Big{ bool operator()(const T& l,const T& r) {return l>r; }};templatestruct Less{ bool operator()(const T& l,const T& r) {return l class Compare>class Heap//Binary Heap {public: Heap() {} void HeapSort(T* a,size_t size) {_a .reserve(size); for(size_t i=0;i =0;--i) {Adjustdown(i);} print(_a,size);} void Adjustup(size_t child) {Compare com; size_t parent =(child-1)/2; while(child> 0) {if(com(_a[child],_a[parent])) {swap(_a[parent],_a[child]); child=parent; parent=(child-1)/2;} else {break ;}}} void Adjustdown(size_t parent) {size_t child =parent*2+1; while(child<_a.size()) {Compare com; if(child+1<_a.size()&&com( _a[child+1],_a[child])) {++child;} if(c om(_a[child],_a[parent])) {swap(_a[parent],_a[child]); parent=child; child=parent*2+1;} else {break;}}} bool Empty( ) {return _a.size()==0;} T& top() {assert(!_a.empty()); return _a[0];} void Push(const T& x) {_a.push_back(x); size_t _size=_a.size(); Adjustup(_size-1); print(_a,_size);} void Pop() {size_t _size=_a.size(); assert(_size>0); swap(_a[0 ],_a[_size-1]); _a.pop_back(); _size=_a.size(); Adjustdown(0); print(_a,_size);} void print(vector a,size_t size) { for(int i=0;i _a;};template  class Compare=Big>class PriorityQueue//Priority queue {public: void Push(const T& x) {hp.Push(x);} void Pop() {hp.Pop();} int Top() { return hp.top(); }protected: Heap hp;};void test(){ int Tree[]={23,12,33,45,15,46,17,78,59}; Heap h1; h1.HeapSort(Tree,sizeof(Tree)/sizeof(Tree[0]));}void test2(){ int arr[] = {12, 10, 43, 23, 22, 4 5, 67,9 }; Heap h1; h1.HeapSort(arr, sizeof(arr)/sizeof(arr[0])); Heap h2; h2.HeapSort(arr, sizeof (arr)/sizeof(arr[0])); }void test3(){ PriorityQueue pq; pq.Push(1); pq.Push(23); pq.Push(33); pq. Push(46); pq.Push(15); pq.Push(43); pq.Push(27); pq.Push(81); pq.Push(19); pq.Push(10); pq.Push (11); cout<

Leave a Comment

Your email address will not be published.