Can someone explain to me why this makes sense (note that heap
is a vector<int>
):
// Heap Sort
int parent = 0;
int leftChild = (parent * 2) + 1;
int rightChild = (parent * 2) + 2;
// This conditional works fine. Code doesn't enter block when heap.size() is zero.
while (leftChild < heap.size()) {}
However:
// Code does enter this block when heap.size() is 0? Why?
while (leftChild < (heap.size() - 1) {}
I get the sense that this is occurring because -1
is somehow being interpreted as 'truthy', but I don't understand how leftChild
(which by default is 1
can ever be less than 0
or -1
.