Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- template <class T>
- class PriorityQueue{
- private:
- vector<T> heap;
- int size = 0;
- int getLeft(int index) const {return index * 2 + 1;}
- int getRight(int index) const {return index * 2 + 2;}
- int getParent(int index) const {return (index + 1) / 2 - 1;}
- void heapify(int index){
- int left = getLeft(index),
- right = getRight(index),
- min = index;
- if(left < size && heap[left] < heap[min])
- min = left;
- if(right < size && heap[right] < heap[min])
- min = right;
- if(min != index){
- swap(heap[min], heap[index]);
- heapify(min);
- }
- }
- public:
- //c-tors & d-tor
- PriorityQueue() = default;
- PriorityQueue(int size) : heap(size){}
- ~PriorityQueue() = default;
- void enqueue(T item){
- //Check if there is enough room in vector
- if(heap.size() >= ++size){
- heap[size - 1] = item;
- }else{
- heap.push_back(item);
- }
- //bubble up to correct position in heap
- int curr = size - 1, parent = getParent(curr);
- while(curr != 0 && heap[curr] < heap[parent]){
- swap(heap[curr], heap[parent]);
- curr = parent;
- parent = getParent(curr);
- }
- }
- T dequeue(){
- T temp = heap[0];
- swap(heap[0], heap[--size]);
- heapify(0);
- return temp;
- }
- };
- int main(){
- PriorityQueue<int> p;
- p.enqueue(4);
- p.enqueue(3);
- p.enqueue(2);
- p.enqueue(100);
- p.enqueue(5);
- for(int i = 0; i < 5; i++)
- cout << p.dequeue() << endl;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement