| Interactive Data Structure
Visualizations Priority Queue |
The reason we implement a priority queue using a heap is to improve the effiiciency of its operations. When we implement a priority queue with an array, the efficiency of one of the two operations will be O(n). If the array is kept in priority order, the enqueue operation is linear. If it is not kept in sorted order, the dequeue operation is linear. Using a heap, the execution time efficiency of both the enqueue and dequeue operations is O(log n). Each operation requires traveling along one branch of the tree, at most, which is log n. Using a heap to implement a priority queue, we will always have the element of highest priority in the root node of the heap.
When watching the animation notice that initially new elements are added to the heap by adding them to the next available node in the right-most position on the lowest level of the tree. This element is then repositioned by moving it up the branch toward the root until it finds an element greater than itself along the branch. It positions itself below that element. Along the path up the branch, the node is swapped with its parent until it is repositioned. The value in the root node of every heap always contains the largest value. On a dequeue operation this value is extracted from the tree. The value in the right-most position on the lowest level of the tree is then moved into the root node. The value is then "sifted' down the maximum branch until it properly repositioned.