This article is to make sure when you use heap library in the real interview, the interviewer ask you details about it, you won’t fail.
PQ is implemented using binary heap tree.
Binary heap tree is
- It’s a complete binary tree.
- Could be max heap or min heap. The parent and child follow the relationship in figure.
- the tree is represented by array.
There’re mainly two methods:
1.Insert using heaplify up.
- Step1: Append the inserted val in the end of heap array.
- Step2: heaplify up till right position.
- Step1: Swap the first value with end value in the heap array
- Step2: heaplify down till right position.
- Step3: pop the last element in the heap array.
Both take O(log n) running time.