Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef STACKADT_H
- #define STACKADT_H
- #include "HeapADT.h"
- #include <string>
- using namespace std;
- template <typename E> class Heap /*: public HeapADT<E>*/
- {
- private:
- E* heap;
- int maxSize;
- int n;
- void swap(E A[], int i, int j) {
- E aux = A[i];
- A[i] = A[j];
- A[j] = aux;
- }
- void heapfy(int pos){
- int leftTemp, rightTemp, heapTemp;
- leftTemp = left(pos);
- rightTemp = right(pos);
- if((heap[pos] < heap[leftTemp]) || (heap[pos]< heap[rightTemp])) {
- if(heap[leftTemp] > heap[rightTemp]) {
- swap(heap, pos, leftTemp);
- heapTemp = leftTemp;
- }
- else {
- swap(heap,pos,rightTemp);
- heapTemp = rightTemp;
- }
- heapfy(heapTemp);
- }
- }
- bool prior(int a, int b)
- {
- return (a>b);
- }
- public:
- Heap(E* h, int num, int max) {
- heap = h;
- n = num;
- maxSize = max;
- buildMaxHeap();
- }
- int size() const{
- return n;
- }
- bool isLeaf(int pos) const {
- return (pos >= n/2) && (pos < n);
- }
- int left(int pos) const {
- return 2*pos + 1;
- }
- int right(int pos) const {
- return 2*pos + 2;
- }
- int parent(int pos) const {
- return (pos-1)/2;
- }
- void buildMaxHeap() {
- for (int i=n/2-1; i>=0; i--) {
- heapfy(i);
- }
- }
- void insert(const E& it) {
- if (n < maxSize) {
- int curr = n++;
- heap[curr] = it;
- while ((curr!=0) &&
- (prior(heap[curr], heap[parent(curr)]))) {
- swap(heap, curr, parent(curr));
- curr = parent(curr);
- }
- }
- else{
- string strAux = "Heap is full!";
- return strAux;
- }
- }
- E removefirst() {
- if(n > 0){
- swap(heap, 0, --n);
- if (n != 0){
- heapfy(0);
- }
- return heap[n];
- }
- else{
- string strAux = "Heap is empty";
- return strAux;
- }
- }
- E remove(int pos) {
- if((pos >= 0) && (pos < n)){
- if (pos == (n-1)){
- n--; }
- else
- {
- swap(heap, pos, --n);
- while ((pos != 0) &&
- (prior(heap[pos], heap[parent(pos)]))) {
- swap(heap, pos, parent(pos));
- pos = parent(pos);
- }
- if (n != 0) {
- heapfy(pos);
- }
- }
- return heap[n];
- }
- else{
- string strAux = "Bad position";
- return strAux;
- }
- }
- };
- #endif // STACKADT_H
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement