Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- using namespace std;
- class PriorityQueue
- {
- private:
- int* arr;
- int sz;
- void up(int i)
- {
- while (i != 0 && arr[i] > arr[(i - 1) / 2])
- {
- swap(arr[i], arr[(i - 1) / 2]);
- i = (i - 1) / 2;
- }
- }
- void down(int i)
- {
- while (i < sz / 2)
- {
- int maxI = 2 * i + 1;
- if (2 * i + 2 < sz && arr[2 * i + 2] > arr[2 * i + 1])
- maxI = 2 * i + 2;
- if (arr[i] >= arr[maxI])
- return;
- swap(arr[i], arr[maxI]);
- i = maxI;
- }
- }
- public:
- PriorityQueue(int k)
- {
- sz = 0;
- arr = new int[k];
- }
- ~PriorityQueue()
- {
- delete arr;
- }
- void push(int value)
- {
- arr[sz++] = value;
- up(sz - 1);
- }
- void pop()
- {
- if (sz > 0)
- {
- swap(arr[0], arr[--sz]);
- down(0);
- }
- else
- return;
- }
- bool empty()
- {
- return sz == 0;
- }
- const int& top()
- {
- return arr[0];
- }
- int size()
- {
- return sz;
- }
- };
- void error_msg(bool check)
- {
- if (!check)
- cout << "Error occured\n";
- }
- int main()
- {
- PriorityQueue Q(10);
- Q.push(1); Q.push(4);
- Q.push(2); Q.push(8);
- cout << Q.size();
- error_msg(Q.size() == 4);
- error_msg(Q.top() == 8);
- Q.pop();
- cout << Q.size();
- error_msg(Q.top() == 4);
- Q.pop();
- cout << Q.size();
- error_msg(Q.top() == 2);
- Q.pop();
- cout << Q.size();
- error_msg(Q.top() == 1);
- Q.pop();
- cout << Q.size();
- error_msg(Q.empty());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement