I've never had my C++ code reviewed before so I'd appreciate any feedback. Although my main focus was not on the implementation of the algorithm itself, any suggestions regarding improving it would be welcome. I'm mostly looking for C++ related feedback though.
#include <iostream>
#include <vector>
using namespace std;
class MinHeap {
public:
void push(int num) {
/* add num to end of the heap and rearrange by up-heap */
heap.push_back(num);
int ind = heap.size() - 1;
if (heap.size() > 1) {
int par = parent_index(ind);
while (heap[ind] < heap[par]) {
swap(heap[ind], heap[par]);
ind = par;
if (ind == 0) break;
par = parent_index(ind);
}
}
}
void pop() {
/* pop the element at the of the heap and finding a new top
by replacing with the last element and performing a down-heap */
if (heap.size() == 1) heap.pop_back();
else if (heap.size() > 1) {
swap(heap[0], heap.back());
heap.pop_back();
int ind = 0;
int min_c = get_min_child(ind);
while (heap[min_c] < heap[ind]) {
swap(heap[min_c], heap[ind]);
ind = min_c;
if (child_count(ind) == 0) break;
min_c = get_min_child(ind);
}
}
}
int top() {
/* return element at the top of the heap (should be the min) */
return heap.front();
}
private:
vector<int> heap;
int get_min_child(int index) {
/* find the smaller child of a node given by index */
if (index < heap.size() - 2) {
int left = left_child_index(index);
int right = right_child_index(index);
return (heap[left] < heap[right]) ? left : right;
}
else if (index < heap.size() - 1) {
return left_child_index(index);
}
else throw invalid_argument("node has no children");
}
int parent_index(int index) {
/* return index of parent node */
if (index > 0) {
return (index - 1) / 2;
}
else throw out_of_range("Trying to access root parent");
}
int child_count(int index) {
/* return the number of children a given node has */
if (2*index + 2 < heap.size()) return 2;
else if (2*index + 1 < heap.size()) return 1;
else return 0;
}
int left_child_index(int index) {
int ind = 2*index + 1;
if (ind < heap.size()) return ind;
else throw out_of_range("Index out of range");
}
int right_child_index(int index) {
int ind = 2*index + 2;
if (ind < heap.size()) return ind;
else throw out_of_range("Index out of range");
}
};