I was studying BST tree for heap sort.
void heapSort(int arr[], int n){
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
-----------
----------
}
It shows that,right most node of tree's 2nd last level index is always n/2-1.
Please Can anyone show me simple math proof of that.Thanks
It's not. The heapify algorithm starts at the first node in the heap that has children. So in the example heap, the heapify algorithm starts at the node labeled 17.
Assuming zero-based indexing (meaning the root node is at index 0), the parent of the
i
th node is(i-1)/2
. So if then
passed to the function is the number of nodes, then the index of the last node isn-1
, and the parent of the last node((n-1)-1)/2
which is the same asn/2 - 1
.