Priority queue: queue that allows us to keep a prioritized list of items
Operations:
- Insert a new item into the queue
- Get the value of the highest priority item
- Remove the highest priority item from the queue
For a limited number of set of priorities, we can use a linked list.
For a huge number of priorities, the heap data structure is one of the most efficient ones we can use to implement a priority queue.
All heaps use a "complete binary tree".
complete binary tree
How to take 12 out of the heap?
Process:
1. 12 is extracted
2. 2 (bottom-left) goes to where 12 was
3. Pick 10 (10 > 7) and swap 2 and 10.
4. Swap 2 and 8.
Result:
10
/ \
7 8
/ \ / \
3 2 2 4
10, 7, 8, 3, 2, 2, 4
This process is called "reheapification".
How to insert 9?
Result:
12
/ \
9 10
/ \ / \
7 2 8 4
/ \
2 3
Result: 12, 9, 10, 7, 2, 8, 4, 2, 3
Then, rather than with a classical binary tree node, how about implementing a heap with an array??
With some formula, an array-based heap allows us to
Convert your randomly-arranged input array into a maxheap by shuffling around the values.
While there are numbers left in the heap:
A. Remove the biggest value from the heap
B. Place it in the last open slot of the array