SUNY Geneseo Department of Computer Science
Tuesday, February 12
CSci 242, Spring 2013
Prof. Doug Baldwin
kth smallest element in an unsorted array A[1..n]
kthSmallest( A, first, last, k )
if last < first
// array section is empty, error!
else
p = partition( A, first, last ) // as in Quicksort
if k < p-first+1
kthSmallest( A, first, p-1, k )
else if k > p-first+1
kthSmallest( A, p+1, last, k-(p-first+1)
// BUG - k+p doesn’t make sense—changed above to k-(p-first+1)
else
return A[p]
kthesmallest
should pass a k
parameter that reflects the number of small elements before the right-hand section of the arraypartition
has put the kth-smallest element in that position, so returning A[p]
is correct.Quicksort
quicksort( A, first, last )
if first < last
p = partition( A, first, last )
// Assume that here A[first..p-1] ≤ A[p] ≤ A[p+1..last]
quicksort( A, first, p-1 )
quicksort( A, p+1, last )
Execution time analysis for divide-and-conquer
Exam 1 moves to Thursday 2/28