quicksort
Quicksort is a divide-and-conquer algorithm for sorting in the comparison model. Its expected running time is for sorting 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 the computation as a binary tree. Each node of the tree corresponds to one recursive call to the quicksort procedure.
Consider the initial input to the algorithm, some list . Call the Sorted list with th and th elements and These two elements will be compared with some probability . This probability can be determined by considering two preconditions on and being compared:
-
•
or must be chosen as a pivot , since comparisons only occur against the pivot.
-
•
No element between and can have already been chosen as a pivot before or is chosen. Otherwise, would be separated into different sublists in the recursion.
The probability of any particular element being chosen as the pivot is uniform. Therefore, the chance that or is chosen as the pivot before any element between them is . This is precisely
The expected number of comparisons is just the summation over all possible comparisons of the probability of that particular comparison occurring. By linearity of expectation, no independence assumptions are 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.
Title | quicksort |
---|---|
Canonical name | Quicksort |
Date of creation | 2013-03-22 13:59:19 |
Last modified on | 2013-03-22 13:59:19 |
Owner | thouis (3290) |
Last modified by | thouis (3290) |
Numerical id | 13 |
Author | thouis (3290) |
Entry type | Definition |
Classification | msc 68P10 |
Related topic | SortingProblem |