Unit 2: Sorting and Order Statistics: Course Contents
Unit 2: Sorting and Order Statistics: Course Contents
․Course contents:
⎯ Heapsort
⎯ Quicksort
⎯ Sorting in linear time
⎯ Order statistics
․Readings:
⎯ Chapters 6, 7, 8, 9
⎢22 ⎥
⎯ Note: (1) cf. height & depth, (2) Won't improve the overall
complexity of the heap sort.
Unit 2 Y.-W. Chang 8
Tree Height and Depth
․Height of a node: # of edges on the longest simple
downward path from the node to a leaf
․Depth: Length of the path from the root to a node
height = 3 depth = 0
height = 2 depth = 1
height = 1 depth = 2
height = 0 depth = 3
MAX-HEAP-INSERT(A,key)
1. heap-size[A] ← heap-size[A] + 1
2. i ← heap-size[A]
3. while i > 1 and A[PARENT(i)] < key
4. do A[i] ← A[PARENT(i)]
5. i ← PARENT(i)
6. A[i] ← key
․A divide-and-conquer algorithm
⎯ Divide: Partition A[p..r] into A[p..q] and A[q+1..r]; each key in
A[p..q] ≤ each key in A[q+1..r].
⎯ Conquer: Recursively sort two subarrays.
⎯ Combine: Do nothing; quicksort is an in-place algorithm.
QUICKSORT(A, p, r)
/* Call QUICKSORT(A, 1, length[A]) to sort an entire array */
1. if p < r then
2. q ← PARTITION(A, p, r)
3. QUICKSORT(A, p, q)
4. QUICKSORT(A, q+1, r)
RANDOMIZED-PARTITION(A, p, r)
1. i ← RANDOM(p, r)
2. exchange A[p] ↔ A[i]
3. return PARTITION(A, p, r)
RANDOMIZED-QUICKSORT(A, p, r)
1. if p < r then
2. q ← RANDOMIZED-PARTITION(A, p, r)
3. RANDOMIZED-QUICKSORT(A, p, q)
4. RANDOMIZED-QUICKSORT(A, q+1, r)
2h ≥ n!
h ≥ lgn! n
⎛n⎞
= Ω(nlgn) /* Stirling's approx n! > ⎜ ⎟ */
⎝e⎠
․ Thus, any comparison-based sorter takes Ω(nlgn) time in the
worst case.
․ Merge sort and heapsort are asymptotically optimal comparison
sorts.
․ Assume n = 2k.
T(n) = 2T(n/2) + 2
= 2(2T(n/4) + 2) + 2
= 2k-1T(2) + (2k-1 + 2k-2 + … + 2)
= 2k-1 + 2k - 2
= 3n/2 - 2
․ This divide-and-conquer algorithm is optimal!
Unit 2 Y.-W. Chang 29
Selection in Linear Expected Time
Randomized-Select(A,p,r,i)
1. if p = r
2. then return A[p];
3. q ← Randomized-Partition(A,p,r);
4. k ← q – p + 1;
5. if i ≤ k
6. then return Randomized-Select(A,p,q,i);
7. else return Randomized-Select(A,q+1,r, i-k).
․ Randomized-Partition first swaps A[p] with a random element of A
and then proceeds as in regular PARTITION.
․ Randomized-Select is like Randomized-Quicksort, except that we
only need to make one recursive call.
․ Time complexity
⎯ Worst case: 1:n-1 partitions.