Beruflich Dokumente
Kultur Dokumente
5 6
9 7
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 17
Vector-based Heap
Implementation (§2.4.3)
We can represent a heap with n
keys by means of a vector of 2
length n + 1
For the node at rank i 5 6
the left child is at rank 2i
the right child is at rank 2i + 1 9 7
Links between nodes are not
explicitly stored
The leaves are not represented
The cell at rank 0 is not used
Operation insertItem corresponds 2 5 6 9 7
to inserting at rank n + 1 0 1 2 3 4 5
Operation removeMin corresponds
to removing at rank n
Yields in-place heap-sort
Heaps and Priority Queues 18
Merging Two Heaps
3 2
We are given two 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 9 23 20
25 5 11 27
16 15 4 12 6 9 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