quicksort
Quicksort is a divide-and-conquer algorithm
for sorting in thecomparison model. Its expected running time is forsorting values.
Algorithm
Quicksort can be implemented recursively, as follows:
Algorithm Quicksort()
Input: A list of elements
Output: The list in sorted order
if then
return
else
return
Analysis
The behavior of quicksort can be analyzed by considering thecomputation as a binary tree. Each node of the tree corresponds toone recursive call to the quicksort procedure.
Consider the initial input to the algorithm, some list . Call theSorted list with th and th elements and Thesetwo elements will be compared with some probability . Thisprobability can be determined by considering two preconditions on and being compared:
- •
or must be chosen as a pivot , since comparisonsonly occur against the pivot.
- •
No element between and can have already been chosenas a pivot before or is chosen. Otherwise, would beseparated into different sublists in the recursion.
The probability of any particular element being chosen as the pivot isuniform. Therefore, the chance that or is chosen as thepivot before any element between them is . This isprecisely
The expected number of comparisons is just the summation over allpossible comparisons of the probability of that particular comparisonoccurring. By linearity of expectation, no independence assumptionsare necessary. The expected number of comparisons is therefore
(1) | |||||
(2) | |||||
(3) | |||||
(4) |
where is the th Harmonic number.
The worst case behavior is , but this almost never occurs (with high probability it does not occur) with random pivots.