Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <exception>
- #include <iostream>
- using namespace std;
- #ifndef _MINHEAP_
- #define _MINHEAP_
- template <class T>
- class MinHeap{
- private:
- const int initSize = 50;
- T *info;
- int size;
- int maxSize;
- public:
- MinHeap();
- ~MinHeap();
- void MinHeapify(int position);
- bool add(T val);
- T extract();
- bool decreaseKey(int position, T newVal);
- T getVal(int position);
- };
- template <class T>
- MinHeap<T>::MinHeap(){
- this->maxSize = this->initSize;
- this->info = new T[this->maxSize];
- this->size = 0;
- }
- template <class T>
- MinHeap<T>::~MinHeap(){
- delete[] this->info;
- }
- template <class T>
- bool MinHeap<T>::add(T data){
- if (this->size + 1 <= this->maxSize) {
- this->info[this->size] = data;
- this->size++;
- this->decreaseKey(this->size - 1, data);
- return true;
- }
- else {
- this->maxSize += this->maxSize;
- T *temp = new T[this->maxSize];
- copy(this->info, this->info + this->size - 1, temp);
- delete[] this->info;
- this->info = temp;
- this->info[this->size] = data;
- this->size++;
- this->decreaseKey(this->size - 1, data);
- return true;
- }
- return false;
- }
- // Method that builts a mean heap starting from a node
- // position - the node to start from building.
- template <class T>
- void MinHeap<T>::MinHeapify(int position) {
- if (position < (this->size - 1) / 2) {
- int l = 2 * position + 1;
- int r = l + 1;
- int min;
- if (l < this->size && this->info[l] <= this->info[position])
- min = l;
- else
- min = position;
- if (r < this->size && this->info[min] >= this->info[r])
- min = r;
- if (min != position)
- swap(this->info[min], this->info[position]);
- MinHeapify(min);
- }
- }
- // Method that extract an element
- // return - the elements that was extracted
- template <class T>
- T MinHeap<T>::extract() {
- if (this->size > 0) {
- T min = this->info[0];
- this->info[0] = this->info[this->size - 1];
- this->size--;
- this->MinHeapify(0);
- return min;
- }
- cout << "Heap is empty!";
- return -1;
- }
- template <class T>
- bool MinHeap<T>::decreaseKey(int position, T newVal){
- if (position >= this->size || position < 0){
- cout << "Position out of bounds!" << endl;
- return false;
- }
- if (this->info[position] < newVal) {
- cout << "Bad new value *bigger*" << endl;
- return false;
- }
- this->info[position] = newVal;
- while (position > 0 && this->info[(position - 1) / 2] > this->info[position]) {
- swap(this->info[(position - 1) / 2], this->info[position]);
- position = (position - 1) / 2;
- }
- return true;
- }
- template <class T>
- T MinHeap<T>::getVal(int position){
- if (position > this->size || position <= 0){
- cout << "Position out of bounds!" << endl;
- return 0;
- }
- else {
- return this->info[position];
- }
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment