Skip to content

Instantly share code, notes, and snippets.

@bexp
Created October 17, 2017 04:15
Show Gist options
  • Save bexp/2d9d94efea6097993936d6350697c80b to your computer and use it in GitHub Desktop.
Save bexp/2d9d94efea6097993936d6350697c80b to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
using namespace std;
// Max Heap impl
struct PriorityQueue {
private:
vector<int> A;
int parent(int i) {
return (i - 1) /2;
}
size_t left(int i) {
return (2*i + 1);
}
size_t right(int i) {
return (2*i + 2);
}
void print() {
for (auto it = A.begin(); it != A.end(); it++) {
cout << *it << ", ";
}
cout << endl;
}
//node at index i and it's two children
//violates heap property
void heapify_down(int i) {
//get left and right children
int largest = i;
size_t l = left(i);
size_t r = right(i);
//compare A[i] with left and right child
//to find max value
if (l < size() && A[l] > A[i]) {
largest = l;
}
if (r < size() && A[r] > largest) {
largest = r;
}
//swap with child having greatest value
// and hepify down the child
if (largest != i) {
swap(A[i], A[largest]);
}
}
//recursive heapify_up algo
void heapify_up(int i) {
//check if node at i and it's parent violates heap property
int p = parent(i);
if (i && (A[p] < A[i])) {
cout << "parent:" << p << " for: " << i << " violates \n";
swap(A[i], A[p]);
heapify_up(p);
}
}
public:
size_t size() const {
return A.size();
}
bool empty() {
return A.size() == 0;
}
void push(int key) {
A.push_back(key);
heapify_up(size() - 1);
print();
}
void pop() {
if (empty())
return;
A[0] = A.back();
A.pop_back();
heapify_down(0);
}
int max() {
if (empty())
return -1;
return A.at(0);
}
};
// To execute C++, please define "int main()"
int main() {
PriorityQueue pq;
pq.push(1);
pq.push(10);
pq.push(-11);
pq.push(4);
pq.push(6);
while (!pq.empty()) {
cout << pq.max() << ", ";
pq.pop();
}
cout << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment