Quick Sort
Quick Sort
BASIC IDEA
Pick one element in the array, which
will be the pivot.
Make one pass through the array,
called a partition step, re-arranging
the entries so that:
• entries smaller than the pivot are to
the left of the pivot.
• entries larger than the pivot are to
the right
BASIC IDEA
Recursively apply quicksort to the part
of the array that is to the left of the
pivot, and to the part on its right.
How to partition?
PARTITIONING (QUICKSORT )
choose pivot: 4 3 6 9 2 4 3 1 2 1 8 9 3 5 6
search: 436924312189356
swap: 433924312189656
search: 433924312189656
swap: 433124312989656
search: 433124312989656
swap: 433122314989656
search: 4 3 3 1 2 2 3 1 4 9 8 9 6 5 6 (L > R)
swap with pivot: 1 3 3 1 2 2 3 4 4 9 8 9 6 5 6
6
ANALYSIS OF QUICKSORT—BEST
CASE
7
PARTITIONING AT VARIOUS LEVELS
8
BEST CASE II
We cut the array size in half each time
So the depth of the recursion in log2n
At each level of the recursion, all the
partitions at that level do work that is
linear in n
O(log2n) * O(n) = O(n log2n)
Hence in the average case, quicksort has
time complexity O(n log2n)
What about the worst case?
9
ANALYSIS OF QUICKSORT—WORST
CASE
11
WORST CASE FOR QUICKSORT
In the worst case, recursion may be n levels
deep (for an array of size n)
But the partitioning work done at each level
is still n
O(n) * O(n) = O(n2)
So worst case for Quicksort is O(n2)
When does this happen?
⚫ When the array is sorted to begin with!
12
TYPICAL CASE FOR QUICKSORT
13
CHOOSING THE PIVOT