Randomized Quick Sort
Randomized Quick Sort
Divide: Partition (rearrange) the array A[p….r] into two (possibly empty) subarrays A[p…q-
1] and A[q+1……r] such that each element of A[p…..q-1] is less than or equal to A[q], which
is, in turn, less than or equal to each element of A[q+1……r]. Compute the index q as part of
this partitioning procedure.
Conquer: Sort the two subarrays A[p…..q-1] and A[q+1……r] by recursive calls to quicksort.
Combine: Because the subarrays are already sorted, no work is needed to combine them: the
entire array A[p….r] is now sorted.
The four regions are maintained by the procedure PARTITION on a subarray A[p…..r]. The
values in A[p….i] are all less than or equal to x, the values in A[i+1….j-1] are all greater than x, and
A[r]=x. The subarray A[j…..r-1] can take on any values.
The final two lines of PARTITION finish up by swapping the pivot element with the leftmost element
greater than x, thereby moving the pivot into its correct place in the partitioned array, and then
returning the pivot’s new index
In this version of Quick Sort where the rightmost element is chosen as a pivot, the worst occurs in the
following cases.
1) Array is already sorted in the same order.
2) Array is already sorted in reverse order.
It is so because in these cases, the PARTITION routine produces one subarray with n-1 elements and
the other subarray with zero element, as shown in the example:
Hence, we see that in the case of quick sort, deterministic selection of the pivot element can often lead
to worst case.
So, we need to randomize the algorithm.
In randomized Quick Sort, instead of always using A[r] as the pivot, we will select a randomly
chosen element from the subarray A[p……r]. We do so by first exchanging element A[r] with an
element chosen at random from A[p….r]. By randomly sampling the range p,……, r, we ensure
that the pivot element x =A[r] is equally likely to be any of the r – p + 1 elements in the subarray.
The changes to PARTITION and QUICKSORT are small. In the new partition procedure, we
simply implement the swap before actually partitioning:
Example:
We will take the same array as taken, while illustrating the deterministic version of Quick Sort,
and see the difference:
Analysis:
Let T(n) be the worst-case time for the procedure QUICKSORT on an input of size n. We
have the recurrence
since we can pick the constant c large enough so that the c(2n-1) term dominates the O(n)
term. Thus, T(n) = O(n2)
❖ Average Case: