Some of the earliest randomized algorithms included algorithms for sorting a set of numbers, and the related problem of finding the
th smallest element in
. The main idea behind these algorithms is the use of random sampling: a randomly chosen member of
is unlikely to be one of its largest or smallest elements; rather, it is likely to be “near the middle.” Extending this intuition suggests that a random sample of elements from
is likely to be spread “roughly uniformly” in
. We now describe randomized algorithms for sorting and selection based on these ideas.
Algorithm RQS is an example of a randomized algorithm-an algorithm that makes random choices during execution. It is inspired by the Quicksort algorithm. We assume that the random choice in Step 1 can be made in unit time. What can we prove about the running time of RQS?
We now analyze the expected number of comparisons in an execution of RQS. Comparisons are performed in Step 2, in which we compare a randomly chosen element to the remaining elements. For
, let
denote the element of rank
(the
th smallest element) in the set
. Define the random variable
to assume the value
if
and
are compared in an execution, and the value 0 otherwise. Thus, the total number of comparisons is
(8.9) |
By linearity of expectation the expected number of comparisons is
(8.10) |