Quicksort: Quicksort: Advantages and Disadvantages Quicksort
Quicksort: Quicksort: Advantages and Disadvantages Quicksort
Quicksort
Outlines: Quicksort
1
Quicksort
Quicksort pros:
Sorts in place
Sorts O(n lg n) in the average case
Very efficient in practice
Quicksort cons:
Sorts O(n2) in the worst case
not stable
does not preserve the relative order of elements with equal
keys
Quicksort
2
Quicksort
Quicksort
Small instance has n ≤ 1
Every small instance is a sorted instance
To sort a large instance:
select a pivot element from out of the n
elements
Partition the n elements into 3 groups left, middle
and right
The middle group contains only the pivot
element
All elements in the left group are ≤ pivot
All elements in the right group are ≥ pivot
Sort left and right groups recursively
Answer is sorted left group, followed by middle
group followed by sorted right group
6
3
Example
6 2 8 5 11 10 4 1 9 7 3
2 5 4 1 3 6 7 9 10 11 8
Quicksort Code
Quicksort(A, p, r)
{
if (p < r)
{
q = Partition(A, p, r)
Quicksort(A, p, q-1)
Quicksort(A, q+1, r)
}
}
4
Partition
10
5
In-Place Partition Example
A = {2, 8, 7, 1, 3, 5, 6, 4}
i pj r pi j r
2 8 7 1 3 5 6 4 2 8 7 1 3 5 6 4
pi j r pi j r
2 8 7 1 3 5 6 4 2 8 7 1 3 5 6 4
p i j r p i j r
2 1 7 8 3 5 6 4 2 11 33 8 7 5 6 4
p i j r p i r
2 11 33 8 7 5 6 4 2 11 33 8 7 5 6 4
p i r
2 11 33 4 7 5 6 8
11
12
6
Choice Of Pivot
13
Choice Of Pivot
14
7
Choice Of Pivot
If A[6].key = 30, A[13].key = 25, and
A[20].key = 10, A[13] becomes the pivot
pivot
15
16
8
Partitioning Example Using
Additional Array
A 6 2 8 5 11 10 4 1 9 7 3
B 2 5 4 1 3 6 7 9 10 11 8
17
Runtime of Quicksort
Worst case:
every time nothing to move
pivot = left (right) end of subarray
(n2)
0123456789
0 123456789
n
89
8 9
18
9
Worst Case Partitioning
19
When n > 1,
T(n) = T(|left|) + T(|right|) + (n)
10
Worst Case Partitioning
Worst-Case Performance (unbalanced):
21
22
11
Best Case Partitioning
23
Average Case
12
Average Case
T (n) T ( n /10) T (9n /10) (n) (n log n)!
Average Case
26
13
Average Case
What happens if we unlucky-split root node, then lucky-split the
resulting size (n-1) node?
We end up with three subarrays, size
1, (n-1)/2, (n-1)/2
n (n)
(n-1)/2 (n-1)/2
27
14
Review: Analyzing Quicksort
29
15