I'm reading the book "Cracking the Coding Interview: 6th Edition" and I'm confused on their definition of "min-heaps" and how they say "Extract Minimum Element" works.
The way they say that Extract Minimum Element is implemented is as follows:
First, we remove the minimum element and swap it with the last element in the heap (the bottommost, rightmost element). Then, we bubble down this element, swapping it with one of its children until the min-heap property is restored.
Do we swap it with the left child or the right child? That depends on their values. There's no inherent ordering between the left and right elements, but you'll need to take the smaller one in order to maintain the min-heap ordering.
This algorithm will also take O(log n) time.
Then they show the following diagram describing how min-heap's "Extract Minimum Element" method would work:
My questions are as follows:
- In the example shown in the image above, how is 80 the "bottommost, rightmost" element of the min-heap prior to when we ran the "extract minimum element" method? It couldn't have been below 88, right, because 88 is greater than 80? Is this just a mistake made by the book?
- How is this algorithm O(log n) time? I would think that it would take O(n) time in order to find the bottommost, rightmost element of the min-heap, as in the worst case scenario, we'd need to search through every node to find a node which doesn't have a sibling on the right (or if the all leaf nodes are at the same level and that level has the maximum number of nodes). Do we maintain a reference to the min-heap's rightmost, bottommost element or something within the heap, so that we can access it more easily?