Heapsort: Comp 122, Spring 2004
Heapsort: Comp 122, Spring 2004
Max-heap as a binary
tree. 26
24 20
18 17 19 13
24
14 20
18
14
24 17 19 13
12 14
18 11
BuildMaxHeap(A)
1. heap-size[A] length[A]
2. for i length[A]/2 downto 1
3. do MaxHeapify(A, i)
24 21 23 22 36 29 30 34 28 27
Initial Heap:
(not max-heap) 24
21 23
22 36 29 30
34 28 27
heapsort - 15 Comp 122 Lin / Devi
BuildMaxHeap – Example
MaxHeapify(10/2 = 5)
MaxHeapify(4)
MaxHeapify(3) 24
36
MaxHeapify(2)
MaxHeapify(1)
21
34
24
36 30
23
28
34
22
24 36
27
21 29 30
23
34
22 28
24 27
21
lg n
T(BuildMaxHeap) h
h 0 2
h
lg n
n
h 0 2
h 1
O ( h)
h
h
, x 1 / 2 in (A.8)
h 0 2
lg n h
O n h
1/ 2
h 0 2 (1 1 / 2) 2
2
lg n h h
O n h O n h
h 0 2 h 0 2
O ( n)
26
24 20
18 17 19 13
12 14 11
heapsort - 22 Comp 122 Lin / Devi
Algorithm Analysis
HeapSort(A)
1. Build-Max-Heap(A)
2. for i length[A] downto 2
3. do exchange A[1] A[i]
In-place 4. heap-size[A] heap-size[A] – 1
5. MaxHeapify(A, 1)
Not Stable
Heap-Extract-Max(A)
1. if heap-size[A] < 1
2. then error “heap underflow”
3. max A[1]
4. A[1] A[heap-size[A]]
5. heap-size[A] heap-size[A] - 1
6. MaxHeapify(A, 1)
7. return max
Heap-Insert(A, key)
1 heap-size[A] heap-size[A] + 1
2 A[heap-size[A]] –
3 Heap-Increase-Key(A, heap-size[A], key)