Sort
Sort
Quicksort
Quicksort: Illustration
1. Selection: Pick a pivot a[k].
i
Quicksort 3
Quicksort Example
• Select the pivot.
Pivot
89 56 63 72 41 34 95
• Put the smalls on the left and bigs on the right.
< pivot > pivot
56 63 41 34 72 89 95
• Continue recursively.
Pivot Pivot
56 63 41 34 89 95
34 41 56 63 89 95
• Finish.
34 41 56 63 72 89 95
Quicksort 4
Partition Example
15 12 3 21 25 3 9 8 18 28 5
• Here, p = 15.
start 15 12 3 21 25 3 9 8 18 28 5
↑ ↑
i j
seek 15 12 3 21 25 3 9 8 18 28 5
↑ ↑
i j
swap 15 12 3 5 25 3 9 8 18 28 21
↑ ↑
i j
seek 15 12 3 5 25 3 9 8 18 28 21
↑ ↑
i j
swap 15 12 3 5 8 3 9 25 18 28 21
↑ ↑
i j
seek 15 12 3 5 8 3 9 25 18 28 21
↑ ↑
j i
f inish 9 12 3 5 8 3 15 25 18 28 21
↑ ↑
j i
Other Considerations
• Correctness: We need to consider two factors
– Since the algorithm is recursive, does it
terminate?
– When it does terminate, does it return a sorted
list?
• Optimization:
– What happens if we sort small subsequences
with another algorithms?
– What if we ignore small subsequences? That
is, we use Quicksort on subarrays larger than
some threshold. Can we then finish sorting
with another algorithm for increased
efficiency? (Hint: The array is now mostly
sorted.)
Quicksort 10
Analyzing Quicksort
• Partition can be done in time O(n), where n is the
size of the array. Can you prove this?
• The cost of all calls to partition at any depth in the
recursion has time complexity O(n), where n is
the size of the original array. Can you prove this?
• Thus, the complexity of Quicksort is the
complexity of partition times the depth of the
furthest recursive call.
• Example:
0 15 12 3 21 25 3 9 8 18 28 5
1 9 12 3 5 8 3 15 25 18 28 21
2 8 3 3 5 9 12 15 21 18 25 28
3 5 3 3 8 9 12 15 18 21 25 28
4 3 3 5 8 9 12 15 18 21 25 28
5 3 3 5 8 9 12 15 18 21 25 28
6 3 3 5 8 9 12 15 18 21 25 28
Quicksort 11
• Worst-Case
– in the worst-case the pivot is always the first or
last element of the subarray.
– In this case, we have
T (n) = T (n − 1) + n
= n + (n − 1) + . . . + 1
= n(n + 1)/2 = O(n2 )
Quicksort 13
• The last step comes from the fact that the two
sums are the same, but in reverse order.
• We have seen that in the best case,
T (n) = O(n log n) and in the worst case,
T (n) = O(n2 ).
• We guess that Ta (n) ≤ an log n + b, for two
positive constants a and b.
• We will prove this by induction.
Quicksort 14
• Substituting, we get
2b 2a X
n−1
Ta (n) = n+ (n − 1) + k log k
n n
k=1
³ ´
2b 2a 1 2 1
≤ n + (n − 1) + n log n − n2
n n 2 8
2b a
= n + 2b − + an log n − n
n 4
2b a
= an log n + b + (n + b − − n)
n 4
a
≤ an log n + b + (n + b − n)
4
≤ an log n + b.