Professional Documents
Culture Documents
2
5
9
Heaps
6
7
Heaps
Additional methods
Applications:
PQ Sorting
Can we do better?
Algorithm PQ-Sort(S, C)
Input sequence S, comparator C
for the elements of S
Output sequence S sorted in
increasing order according to C
P priority queue with
comparator C
while S.empty ()
e S.front(); S.eraseFront()
P.insert (e, )
while P.empty()
e P.removeMin()
S.insertBack(e)
Heaps
Two Paradigms of PQ
Sorting
PQ via selection
sort
Heaps
PQ via insertion
sort
Heaps
Min heap
Heaps
5
9
6
7
last node
5
Height of a Heap
depth keys
0
h1
2h1
Heaps
(9, Jeff)
(6, Mark)
(7, Anna)
Heaps
Method insertItem of
the priority queue ADT
corresponds to the
insertion of a key k to
the heap
The insertion algorithm
consists of three steps
Heaps
2
5
9
z
7
insertion node
2
5
9
6
7
Upheap
5
9
1
7
Heaps
2
7
Up-heap
bubbling
Heaps
10
Method removeMin of
the priority queue ADT
corresponds to the
removal of the root key
from the heap
The removal algorithm
consists of three steps
2
5
9
6
7
w
last node
7
Heaps
11
Downheap
After replacing the root key with the key k of the last node, the
heap-order property may be violated
Algorithm downheap restores the heap-order property by
swapping key k along a downward path from the root
Upheap terminates when key k reaches a leaf or a node whose
children have keys greater than or equal to k
Since a heap has height O(log n), downheap runs in O(log n) time
7
5
5
6
Heaps
12
Down-heap
bubbling
Heaps
13
Heaps
14
Heap-Sort
Consider a priority
queue with n items
implemented by a
heap
Heap-sort
Heaps
Sort a sequence of n
elements in O(n log n)
time using a heap-based
PQ
Much faster than
quadratic sorting
algorithms, such as
insertion-sort and
selection-sort
15
Vector-based Heap
Implementation
Heaps
2
5
16
In heap
Stage 1:
Heap
construction
Sorted
In heap
Sorted
Sorted
In heap
Sorted
In heap
Stage 2:
output
Heaps
17
3
8
Heaps
7
3
8
2
5
2
3
8
4
5
6
18
Bottom-up Heap
Construction
Goal: Construct a
heap of n keys using
a bottom-up method
with log n phases
In phase i, pairs of
heaps with 2i 1 keys
are merged into
heaps with 2i11 keys
2i 1
2i 1
2i11
Heaps
19
Example
16
15
25
16
12
5
15
23
11
12
Heaps
20
27
7
23
20
20
Example (contd.)
25
16
5
15
15
16
11
12
4
25
27
9
23
6
12
11
Heaps
20
23
9
27
20
21
Example (contd.)
7
15
16
4
25
6
12
11
23
9
4
5
25
20
15
16
27
8
12
11
Heaps
23
9
27
20
22
Example (end)
10
4
15
16
5
25
8
12
11
23
9
27
20
4
5
15
16
7
25
10
8
12
11
Heaps
23
9
27
20
23
Heaps
24
T 2 h 1 2 h 1 2 2 h 2 3 20 h 1
2T 2 h 1 1 2 h 2 2 h 1 3 21 h 1
2T T 2 h 1 2 h 2 h 1 21 h 1
T 2 h 2 1 h 1 2 2 h 1 1 h 1 2n 1 log 2 n 1
T O n
Heaps
25