Csce411 Random3
Csce411 Random3
Csce411 Random3
Quicksort
Andreas Klappenecker
Overview
Deterministic Quicksort
Randomized Quicksort
Deterministic Quicksort
Quicksort(A,p,r)
if p < r then
Quicksort(A, p,q-1);
Quicksort(A,p+1,r);
Divide-and-Conquer
The design of Quicksort is based on the divide-and-conquer paradigm.
a) Divide: Partition the array A[p..r] into two (possibly empty) subarrays A
[p..q-1] and A[q+1,r] such that
2 1 3 4 7 5 6 8
p i r
i := p-1;
return i+1;
Partition - Loop - Example
2 8 7 1 3 5 6 4 2 1 7 8 3 5 6 4
i p,j r p i j r
2 8 7 1 3 5 6 4 2 1 3 8 7 5 6 4
p,i j r p i j r
2 8 7 1 3 5 6 4 2 1 3 8 7 5 6 4
p,i j r p i j r
2 8 7 1 3 5 6 4 2 1 3 8 7 5 6 4
p,i j r p i r
After the loop, the partition routine swaps the leftmost element of the right
partition with the pivot element:
2 1 3 8 7 5 6 4
p i r
swap(A[i+1],A[r])
2 1 3 4 7 5 6 8
p i r
If partition produces two subproblems that are roughly of the same size,
then the recurrence of the running time is
The array U contains n/5 elements. Thus, n/10 elements of U are larger
(smaller) than m, since m is the median of U . Since each element in U is a
median itself, there are 3n/10 elements in A that are larger (smaller) than m.
Randomized-Quicksort(A,p,r)
if p < r then
q := Randomized-Partition(A,p,r);
Randomized-Quicksort(A, p,q-1);
Randomized-Quicksort(A,p+1,r);
Partition
Randomized-Partition(A,p,r)
i := Random(p,r);
swap(A[i],A[r]);
Partition(A,p,r);
Almost the same as Partition, but now the pivot element is not the
rightmost element, but rather an element from A[p..r] that is chosen
uniformly at random.
Goal
Let Zij = {zi, ..., zj} denote the set of elements between zi and zj,
including these elements.
Thus, Xij is an indicator random variable for the event that the i-th
smallest and the j-th smallest elements of A are compared in an
execution of quicksort.
Number of Comparisons
Since each pair of elements is compared at most once by quicksort, the
number X of comparisons is given by
n−1
� n
�
X= Xij
i=1 j=i+1
If zi < x < zj then zi and zj will land in different partitions and will
never be compared afterwards.