Professional Documents
Culture Documents
Lec8 PDF
Lec8 PDF
http://ocw.mit.edu
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.
Lecture 8
Sorting I: Heaps
Readings
CLRS 2.1, 2.2, 2.3, 6.1, 6.2, 6.3 and 6.4
Sorting Review
Insertion Sort
key
(n2) algorithm
4 6
1 3
2 5
4 6
1 2
3 4
2 4
1 3
1 2 4 5
2 4 5 6
Merge Sort
Divide n-element array into two subarrays of n/2 elements each. Recursively sort sub-arrays
using mergesort. Merge two sorted subarrays.
Lecture 8
Sorting I: Heaps
L
(n) time
2 4 5 7
(n) auxiliary
A
space
R
1 2 3 6
1 2 2 3 4 5 6 7
A[1: n/2]
A[n/2+1: n]
2 4 5 7
1 2 3 6
Selection Sort
0.
i=1
1.
2.
3.
i = i + 1, stop if i = n
Iterate steps 0-3 n times. Step 1 takes O(n) time. Can we improve to O(lg n)?
Lecture 8
Sorting I: Heaps
i=1
(n ) time
in-place
2
1 16
4
8
6 9
5 7
8
9 4
1 2 3 4 5 6 7 8 9
10 3
2 14
16 14 10 8 7 9
7 3
Data Structure
root A[i]
Node with index i
PARENT(i) = 2i
LEFT(i) = 2i
RIGHT(i) = 2i + 1
Note: NO POINTERS!
3
10
3 2 4 1
Lecture 8
length[A]:
Sorting I: Heaps
heap-size[A]:
heap-size[A]:
length[A]
Lecture 8
Sorting I: Heaps
Example
1 16
2
4
8
7 3
10
1
9 8
6 9
5 7
14
MAX_HEAPIFY (A,2)
heap_size[A] = 10
10 3
1 16
10 3
2 14
4
8
7 3
10
1
9 8
6 9
5 7
1 16
10 3
2 14
4
8
6 9
5 7
8
9 4
7 3
10