Interface 接口
• O(logN) Push -> Sift Up
• O(logN) Pop -> Sift Down • O(1) Top
• O(N) Delete
Heap Application
Priority Queue: Priority queues can be efficiently implemented using Binary Heap because it supports insert(), delete() and extractmax(), decreaseKey() operations in O(logn) time.
The default PriorityQueue is implemented with Min-Heap, that is the top element is the minimum one in the heap. In order to implement a max-heap, you can create your own Comparator:
importjava.util.Comparator;publicclassMyComparatorimplementsComparator<Integer>{publicintcompare( Integer x,Integer y ) {return y - x; }}
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.
Note − In Min Heap construction algorithm, we expect the value of the parent node to be less than that of the child node.
Max Heap Deletion Algorithm
Deletion in Max (or Min) Heap always happens at the root to remove the Maximum (or minimum) value.
Step 1 − Remove root node.
Step 2 − Move the last element of last level to root.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.