Professional Documents
Culture Documents
5 6
9 7
x≤y∧y≤z⇒x≤z
can have the
same key
Performance: Performance:
insertItem takes O(1) time insertItem takes O(n) time
since we can insert the item since we have to find the
at the beginning or end of place where to insert the
the sequence item
removeMin, minKey and removeMin, minKey and
minElement take O(n) time minElement take O(1) time
since we have to traverse since the smallest key is at
the entire sequence to find the beginning of the
the smallest key sequence
depth keys
0 1
1 2
h−2 2h−2
h−1 1
2 1
5 1 5 2
9 7
z 6 9 7
z 6
7 5
5 6 7 6
w w
9 9
Consider a priority
Using a heap-based
queue with n items
priority queue, we can
implemented by means sort a sequence of n
of a heap elements in O(n log n)
the space used is O(n) time
methods insertItem and The resulting algorithm
removeMin take O(log n) is called heap-sort
time
Heap-sort is much
methods size, isEmpty,
faster than quadratic
minKey, and minElement
take time O(1) time sorting algorithms, such
as insertion-sort and
selection-sort
Heaps and Priority Queues 18
Merging Two Heaps
3 2
We are given two
8 5 4 6
heaps and a key k
We create a new heap
with the root node 7
storing k and with the 3 2
two heaps as subtrees 8 5 4 6
We perform downheap
to restore the heap-
2
order property
3 4
8 5 7 6
16 15 4 12 6 7 23 20
25 5 11 27
16 15 4 12 6 7 23 20
25 5 11 27
16 15 4 12 6 9 23 20
15 4 6 23
16 25 5 12 11 9 27 20
15 4 6 23
16 25 5 12 11 9 27 20
4 6
15 5 8 23
16 25 7 12 11 9 27 20
4 6
15 5 8 23
16 25 7 12 11 9 27 20
5 6
15 7 8 23
16 25 10 12 11 9 27 20