Describe a priority queue.
The** priority queue **is an ADT that associates a priority value with each element. The element with the highest priority is the first one dequeued.
- insert() – insert an element with a specified priority value
- first() – return the element with the lowest priority value (the “first” element in the priority queue)
- remove_first() – remove (and return) the element with the lowest priority value
What is the pseudocode for bubbling up or down a heap?
while new priority value < parent’s priority value:
swap new node with parent
while priority > smallest child priority:
swap with smallest child
What are the formula for right child, left child, and parent in a heap?
Why do we use an array for a heap but not other binary trees?
By bubbling up and down, a heap is always complete. A complete tree does not have any gaps when represented as an array. Thus, an array can efficiently represent a heap but is inefficient for other trees.
What are the steps for inserting into a heap?
What are the steps for removing from a heap?
How would you efficiently build a heap out of an array?
We percolate down the first non-leaf element (n//2)-1. Then the subtree rooted at that element’s original position will be a proper heap.
e can repeat this, moving backwards one element at a time from the first non-leaf element, and each time we percolate an element down, the subtree rooted at that element’s original position will be a proper heap.
Once we percolate down the root element, the entire array will represent a proper heap.
How is heapsort implemented?