Read heaps first.
Implementations:
heapq
PriorityQueue
priority_queue
A binary heap uses a complete binary tree.
Recall that complete binary trees:
Inserting into a binary heap:
Swaps happen between levels, and a tree will have lg(n) levels.
Since there are n items to be inserted, insertion will take O(nlogn)
.
Extracting the dominator from a binary heap:
Since a binary heap is a complete binary tree we can implement it using an array.
Example: 2 7 8 1 5 9 3
pushed into min-heap as a tree:
1
2 3
7 5 9 8
But as an array looks like: 1,2,3,7,5,9,8,
.
Notice this is equivalent to a breadth-first traversal.
This image from Wikipedia explains best:
So for some zero-based index i
:
2i + 1
2i + 2
floor((i-1) / 2)
WARNING: Beware zero and one-based version of the above equations. Many references use one-based equations because the math/logic is cleaner, but programmers always use zero-based arrays.
Notice that floor(n/2)
is the index of one or more the the middle items of the array:
floor(n/2)
if n is oddfloor(n/2)
and floor(n/2) - 1
if n is evenTo insert:
parent = heap[floor((i-1)/2)]
Note:
Heap Interface:
min
or max
add
or insert
an elementremove
or delete
an elementWe can store any binary tree in an array without pointers but:
https://en.wikipedia.org/wiki/Binary_heap