Advertisement
AaronThomsen

Priority Queue

Jul 1st, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.74 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. template <class T>
  8. class PriorityQueue{
  9. private:
  10.     vector<T> heap;
  11.     int size = 0;
  12.  
  13.     int getLeft(int index) const {return index * 2 + 1;}
  14.     int getRight(int index) const {return index * 2 + 2;}
  15.     int getParent(int index) const {return (index + 1) / 2 - 1;}
  16.  
  17.     void heapify(int index){
  18.         int left = getLeft(index),
  19.             right = getRight(index),
  20.             min = index;
  21.  
  22.         if(left < size && heap[left] < heap[min])
  23.             min = left;
  24.         if(right < size && heap[right] < heap[min])
  25.             min = right;
  26.  
  27.         if(min != index){
  28.             swap(heap[min], heap[index]);
  29.             heapify(min);
  30.         }
  31.     }
  32. public:
  33.     //c-tors & d-tor
  34.     PriorityQueue() = default;
  35.     PriorityQueue(int size) : heap(size){}
  36.     ~PriorityQueue() = default;
  37.  
  38.     void enqueue(T item){
  39.         //Check if there is enough room in vector
  40.         if(heap.size() >= ++size){
  41.             heap[size - 1] = item;
  42.         }else{
  43.             heap.push_back(item);
  44.         }
  45.  
  46.         //bubble up to correct position in heap
  47.         int curr = size - 1, parent = getParent(curr);
  48.  
  49.         while(curr != 0 && heap[curr] < heap[parent]){
  50.             swap(heap[curr], heap[parent]);
  51.             curr = parent;
  52.             parent = getParent(curr);
  53.         }
  54.     }
  55.  
  56.     T dequeue(){
  57.         T temp = heap[0];
  58.  
  59.         swap(heap[0], heap[--size]);
  60.         heapify(0);
  61.  
  62.         return temp;
  63.     }
  64.  
  65. };
  66.  
  67. int main(){
  68.     PriorityQueue<int> p;
  69.  
  70.     p.enqueue(4);
  71.     p.enqueue(3);
  72.     p.enqueue(2);
  73.     p.enqueue(100);
  74.     p.enqueue(5);
  75.  
  76.     for(int i = 0; i < 5; i++)
  77.         cout << p.dequeue() << endl;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement