Introduction To Algorithms: 6.046J/18.401J/SMA5503
Introduction To Algorithms: 6.046J/18.401J/SMA5503
6.046J/18.401J/SMA5503
Lecture 6
Prof. Erik Demaine
Order statistics
Select the ith smallest of n elements (the
element with rank i).
• i = 1: minimum;
• i = n: maximum;
• i = (n+1)/2 or (n+1)/2: median.
Naive algorithm: Sort and index ith element.
Worst-case running time = Θ(n lg n) + Θ(1)
= Θ(n lg n),
using merge sort or heapsort (not quicksort).
© 2001 by Charles E. Leiserson Introduction to Algorithms Day 9 L6.2
Randomized divide-and-
conquer algorithm
RAND-SELECT(A, p, q, i) ⊳ ith smallest of A[ p . . q]
if p = q then return A[ p]
r ← RAND-PARTITION(A, p, q)
k←r–p+1 ⊳ k = rank(A[r])
if i = k then return A[ r]
if i < k
then return RAND-SELECT(A, p, r – 1, i )
else return RAND-SELECT(A, r + 1, q, i – k )
k
≤≤ A[r]
A[r] ≥≥ A[r]
A[r]
p r q
© 2001 by Charles E. Leiserson Introduction to Algorithms Day 9 L6.3
Example
Select the i = 7th smallest:
66 10
10 13
13 55 88 33 22 11
11 i=7
pivot
Partition:
22 55 33 66 88 13
13 10
10 11
11 k=4
Linearity of expectation.
greater
© 2001 by Charles E. Leiserson Introduction to Algorithms Day 9 L6.22
Choosing the pivot
greater
© 2001 by Charles E. Leiserson Introduction to Algorithms Day 9 L6.24
Analysis (Assume all elements are distinct.)