Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- template<typename T>
- struct Heap {
- explicit Heap(size_t size) {
- _Size = size;
- try {
- _Tree = (T *) malloc( _Size * sizeof(T));
- }
- catch(...){
- std::cerr << "NOMEM" ;
- exit(1);
- }
- }
- Heap() {
- try {
- _Tree = (T *) malloc( _Size * sizeof(T));
- }
- catch(...){
- std::cerr << "NOMEM" ;
- exit(1);
- }
- }
- inline bool is_empty() {
- return _elemSize == 0;
- }
- T top() {
- try{
- if (is_empty()){
- throw;
- }
- return _Tree[0];
- }
- catch (...){
- std::cerr << "Err: Heap is empty" << '\n';
- }
- }
- void push(T value) {
- if (_elemSize == _Size) {
- _resize();
- }
- _Tree[_elemSize++] = value;
- siftUp(_elemSize - 1);
- }
- void pop() {
- if (!is_empty()) {
- _Tree[0] = _Tree[--_elemSize];
- siftDown(0);
- } else {
- std::cerr << "Err: Heap is empty" << '\n';
- }
- }
- void clear() {
- _elemSize = 0;
- }
- ~Heap() {
- free(_Tree);
- }
- private:
- T *_Tree;
- size_t _elemSize = 0;
- size_t _Size = 4;
- void siftUp(size_t index) {
- while (index > 0 && _Tree[index] > _Tree[(index - 1) / 2]) {
- std::swap(_Tree[index], _Tree[(index - 1) / 2]);
- index = (index - 1) / 2;
- }
- }
- void siftDown(size_t index) {
- while (2 * index + 1 < _elemSize) {
- size_t lch = 2 * index + 1;
- size_t rch = 2 * index + 2;
- size_t maxCh = lch;
- if (rch < _elemSize && _Tree[rch] > _Tree[maxCh]) {
- maxCh = rch;
- }
- if (_Tree[index] >= _Tree[maxCh])
- return;
- std::swap(_Tree[index], _Tree[maxCh]);
- index = maxCh;
- }
- }
- void _resize() {
- try {
- _Tree = (T *) realloc(_Tree, _Size * 2 * sizeof(T));
- _Size *= 2;
- }
- catch(...){
- std::cerr << "NOMEM" ;
- exit(1);
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement