#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
We leave the initial index (0) empty to make indexing easier.
vector<int> heap{-1, 13,14,16,24,21,17,19,65,26,32,21};
heap
{ -1, 13, 14, 16, 24, 21, 17, 19, 65, 26, 32, 21 }
unsigned int parent(unsigned int idx) {
return idx / 2;
}
unsigned int leftChild(unsigned int idx) {
return 2*idx;
}
unsigned int rightChild(unsigned int idx) {
return 2*idx + 1;
}
heap[leftChild(1)] // returns value, 1 is the index
14
heap[rightChild(1)]
16
heap[rightChild(3)]
19
Shift things over so that the root of the heap is at index 1. Need to redo the parent, leftChild, rightChild functions.
vector<int> heap{13,14,16,24,21,17,19,65,26,32,23};
heap
{ 13, 14, 16, 24, 21, 17, 19, 65, 26, 32, 23 }
unsigned int parent(unsigned int idx) {
return (idx+1) / 2 - 1;
}
unsigned int leftChild(unsigned int idx) {
return 2*(idx+1) - 1;
}
unsigned int rightChild(unsigned int idx) {
return 2*(idx+1) + 1 - 1;
}
heap[leftChild(0)]
14
heap[rightChild(0)]
16
heap[rightChild(2)]
19
heap.push_back(5);
heap
{ 13, 14, 16, 24, 21, 17, 19, 65, 26, 32, 23, 5 }
// be careful: this doesn't check that the parentIdx is valid!
// causes a segfault!
unsigned int newIdx = heap.size() - 1;
unsigned int parentIdx = parent(newIdx);
while (heap[newIdx] < heap[parentIdx]) {
swap(heap[parentIdx], heap[newIdx]);
newIdx = parentIdx;
parentIdx = parent(newIdx);
}
void insert(vector<int> & heap, int val) {
heap.push_back(val);
unsigned int newIdx = heap.size() - 1;
unsigned int parentIdx = parent(newIdx);
while (newIdx > 0 && heap[newIdx] < heap[parentIdx]) {
swap(heap[parentIdx], heap[newIdx]);
newIdx = parentIdx;
parentIdx = parent(newIdx);
}
}
vector<int> heap{13,14,16,24,21,17,19,65,26,32,23};
insert(heap, 5)
heap
{ 5, 14, 13, 24, 21, 16, 19, 65, 26, 32, 23, 17 }
int findMin(vector<int> & heap) {
return heap[0];
}
int minVal = findMin(heap);
minVal
5
void minDelete(vector<int> & heap) {
heap[0] = heap.back();
heap.pop_back();
unsigned int curIdx = 0;
unsigned int leftIdx = leftChild(curIdx);
unsigned int rightIdx = rightChild(curIdx);
// be careful we don't go over the size of tree
while ((leftIdx < heap.size() && heap[curIdx] > heap[leftIdx])
|| (rightIdx < heap.size() && heap[curIdx] > heap[rightIdx])) {
if (rightIdx >= heap.size() || heap[leftIdx] < heap[rightIdx]) {
swap(heap[curIdx], heap[leftIdx]);
curIdx = leftIdx;
} else {
swap(heap[curIdx], heap[rightIdx]);
curIdx = rightIdx;
}
leftIdx = leftChild(curIdx);
rightIdx = rightChild(curIdx);
}
}
minDelete(heap);
heap
{ 13, 14, 16, 24, 21, 17, 19, 65, 26, 32, 23 }
minDelete(heap);
heap
{ 14, 21, 16, 24, 23, 17, 19, 65, 26, 32 }
Try to do this in-place. For you to implement.