Quick Sort
Quick Sort
2
Quick Sort
88 52
14
31
25 98 30
62 23
79
14 88
98
31 30 23 ≤ 52 ≤ 62
25 79
3
Quick Sort
14 88
98
31 30 23 ≤ 52 ≤ 62
25 79
14,23,25,30,31 62,79,98,88
4
Quick Sort
14,23,25,30,31
52
62,79,88,98
5
Quicksort
Quicksort advantages:
Sorts in place
Sorts O(n lg n) in the average case
Very efficient in practice
Quicksort disadvantages :
Sorts O(n2) in the worst case
not stable
Does not preserve the relative order of elements with equal
keys
Sorting algorithm (stable) if 2 records with same key stay in
original order
But in practice, it’s quick
And the worst case doesn’t happen often … sorted
6
Quicksort
Another divide-and-conquer algorithm:
Divide: A[p…r] is partitioned (rearranged) into
two nonempty subarrays A[p…q-1] and A[q+1…r]
s.t. each element of A[p…q-1] is less than or
equal to each element of A[q+1…r]. Index q is
computed here, called pivot.
Conquer: two subarrays are sorted by recursive
calls to quicksort.
Combine: unlike merge sort, no work needed
since the subarrays are sorted in place already.
7
Quicksort
The basic algorithm to sort an array A consists
of the following four easy steps:
If the number of elements in A is 0 or 1, then return
Pick any element v in A. This is called the pivot
Partition A-{v} (the remaining elements in A) into
two disjoint groups:
A1 = {x A-{v} | x ≤ v}, and
A2 = {x A-{v} | x ≥ v}
return
{ quicksort(A1) followed by v followed by
quicksort(A2)}
8
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
9
Example
6 2 8 5 11 10 4 1 9 7 3
2 5 4 1 3 6 7 9 10 11 8
12
Partition Code
Partition(A, p, r)
{
x = A[r] // x is pivot
i = p - 1
for j = p to r – 1
{
do if A[j] <= x
then
{
i = i + 1
exchange A[i] A[j]
}
}
exchange A[i+1] A[r]
return i+1 partition() runs in O(n) time
}
13
Partition Example A = {2, 8, 7, 1, 3, 5, 6,
i 4}p j 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
14
Partition Example Explanation
Red shaded elements are in the first partition
with values x (pivot)
15