template <typename T> class MaxHeap { public: MaxHeap(int max_size, int cur_size, T data[]) : cur_size_(cur_size), max_size_(max_size) { if (max_size_ < cur_size_) throw logic_error("Maximum size must no more less then the current size!"); heap_ =new T[max_size_ +1]; copy(data, data + cur_size_, heap_ +1); } ~MaxHeap() { delete []heap_; } void MaxHeapify(int i) { int l = left(i); int r = right(i); int largest = i; if (l <= cur_size_ && heap_[l] > heap_[largest]) largest = l; if (r <= cur_size_ && heap_[r] > heap_[largest]) largest = r; if (largest != i) { swap(heap_[largest], heap_[i]); MaxHeapify(largest); } } void BuildMaxHeap() { for (int i = cur_size_ /2; i >=1; i--) { MaxHeapify(i); } } T Maximum() { return heap_[1]; } T ExtractMaximum() { if (cur_size_ <=1) throw logic_error("No element in max heap!"); T max = heap_[1]; heap_[1] = heap_[cur_size_]; cur_size_--; MaxHeapify(1); return max; } void IncreaseKey(int i, T key) { if (key < heap_[i]) throw logic_error("the new key is smaller than current key!"); heap_[i] = key; while (i >1&& heap_[parent(i)] < heap_[i]) { swap(heap_[parent(i)], heap_[i]); i = parent(i); } } void HeapInsert(T key) { if (max_size_ <= cur_size_) throw logic_error("The heap is out of size, can't insert!"); cur_size_++; heap_[cur_size_] = T(-0xFFFF); IncreaseKey(cur_size_, key); } void HeapSort() { int tmp_size = cur_size_; for (int i = tmp_size; i >1; i--) { swap(heap_[1], heap_[i]); cur_size_--; MaxHeapify(1); } // restore the size cur_size_ = tmp_size; } ostream& print(ostream&out) { copy(heap_ +1, heap_ + cur_size_ +1, ostream_iterator<T>(out, "")); returnout; } private: int parent(int i) { return i /2; } int left(int i) { return i *2; } int right(int i) { return i *2+1; } private: int cur_size_; int max_size_; T* heap_; }; template <typename T> ostream&operator<<(ostream&out, MaxHeap<T>& mh) { return mh.print(out); }