quicksort
Quicksort is a divide-and-conquer algorithm
for sorting in the
comparison model. Its expected running time is O(nlgn) for
sorting n values.
Algorithm
Quicksort can be implemented recursively, as follows:
Algorithm Quicksort(L)
Input: A list L of n elements
Output: The list L in sorted order
if n>1 then
p← random element of L
A←{x|x∈L,x<p}
B←{z|z∈L,z=p}
C←{y|y∈L,y>p}
SA←Quicksort(A)
SC←Quicksort(C)
return Concatenate(SA,B,SC)
else
return L
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 L. Call the Sorted list S, with ith and jth elements Si and Sj. These two elements will be compared with some probability pij. This probability can be determined by considering two preconditions on Si and Sj being compared:
-
•
Si or Sj must be chosen as a pivot p, since comparisons only occur against the pivot.
-
•
No element between Si and Sj can have already been chosen as a pivot before Si or Sj 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 Si or Sj is chosen as the pivot before any element between them is 2/(j-i+1). This is precisely pij.
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
n∑i=1n∑j>ipij | = | n∑i=1n∑j>i2j-i+1 | (1) | ||
= | n∑i=1n-i+1∑k=22k | (2) | |||
≤ | 2n∑i=1n∑k=11k | (3) | |||
= | 2nHn=O(nlgn), | (4) |
where Hn is the nth Harmonic number.
The worst case behavior is Θ(n2), 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 |