Heaps are structures designed for quick access to min or max .
But why do you need this? You can simply check each entry in the add to see if it is the smallest or the largest. Thus, you always have the smallest or largest constant time O(1) .
The answer is that heaps allow you to pull out the smallest or largest and quickly find out NEXT the smallest or largest . That is why he called the priority order.
Real world example (not very fair world):
Suppose you have a hospital in which patients are visited according to age. The oldest are always in the first place, regardless of when he / she got in line.
You cannot just keep track of the oldest, because if you pull it out, you do not know the next oldest. To solve this hospital problem, you implement the maximum heap . This heap, by definition, is partially streamlined. This means that you cannot sort patients by their age, but you know that the oldest of them are always at the top, so you can pull the patient out at constant O(1) and rebalance the heap during O(log N) .
More complex example:
Suppose you have a sequence of integers and you want to track median . Median is a number that is in the middle of an ordered array.
Example:
[1, 2, 5, 7, 23, 27, 31]
In the above case, 7 is median because the array containing the smaller numbers [1, 2, 5] has the same size as the larger numbers [23, 27, 31] . Usually, if the array has an even number of elements, the median is the arithmetic mean of two elements in the middle, for example (5 + 7)/2 .
Now, how do you track the median? Having 2 heaps , one minute heap containing numbers smaller than the current median, and a maximum heap containing numbers larger than the current median. Now, if these heaps are always balanced, 2 heaps will contain the same number of elements, or one will have 1 element more than the other.
When you add a new element to the sequence, if the number is less than the current median, you add it to the heap of minutes, otherwise you add it to the maximum heap. Now, if the heaps are not balanced (one heap has more than 1 element more than the other), you pull the element from the largest heap and add to the smallest one. Now they are balanced.