CSCE 411 Lecture 26
« previous | Monday, October 29, 2012 | next »
Deterministic Quicksort
def quicksort arr, p, r
if p < r
q = partition(arr, p,r) #rearrange a[p..r] in place
quicksort(arr, p,q-1)
quicksort(arr, p+1,r)
end
end
def partition arr, p, r
x = arr[r] #select rightmost element as pivot
i = p-1
p.upto(r-1) do |j|
if arr[j] <= x
i += 1
arr[i], arr[j] = arr[j], arr[i]
end
end
arr[i+1], arr[r] = arr[r], arr[i+1]
i+1
end
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) = quicksort (filter xs (< x)) ++ [x] ++ quicksort (filter (>= x))
partition selects a pivot element (Ruby uses last element, Haskell uses first element) and rearranges all items around the pivot (less on left, greater on right)
Analysis
Worst-case is
Better Deterministic Quicksort
find the median of all array elements in linear time:
def median arr
do_something if arr.length < 5
median arr.split(5).map {|subarr| subarr.median_of_5} # finding median of 5 elements requires 6 comparisons
end
Analysis
Worst-case is now
Best Randomized Quicksort
def randomized_partition arr, p, r
i = (p..r).to_a.sample # choose a random index between P and R
arr[i], arr[r] = arr[r], arr[i]
partition arr, p, r
end
Analysis
Let rv count the number of comparisons made in all calls to randomized_partition.
Let denote the ith smallest element of , so sorted is
Let be the set of elements between and including and
Indicator rv indicates whether is compared to , i.e. if either or is seleted as a pivot element.
Since each pair of elemens is compared at most once, number of comparisons is
Therefore, expected number of comparisons is
When do we compare to
if , then they will end up in separate partitions and never be compared.
Therefore, and will be compared iff the first element of to be picked as the pivot element is contained in .
Therefore, .