Quicksort: By: Vimal Awasthi
Quicksort: By: Vimal Awasthi
By:
Vimal Awasthi
Quicksort I
• To sort a[left...right]:
1. if left < right:
1.1. Partition a[left...right] such that:
all a[left...p-1] are less than a[p], and
all a[p+1...right] are >= a[p]
1.2. Quicksort a[left...p-1]
1.3. Quicksort a[p+1...right]
2. Terminate
2
Partitioning (Quicksort II)
• A key step in the Quicksort algorithm is
partitioning the array
– We choose some (any) number p in the array to use as
a pivot
– We partition the array into three parts:
3
Partitioning II
• Choose an array value (say, the first) to use as the
pivot
• Starting from the left end, find the first element
that is greater than or equal to the pivot
• Searching backward from the right end, find the
first element that is less than the pivot
• Interchange (swap) these two elements
• Repeat, searching from where we left off, until
done
4
Partitioning
• To partition a[left...right]:
1. Set p = a[left], l = left + 1, r = right;
2. while l < r, do
2.1. while l < right & a[l] < p, set l = l + 1
2.2. while r > left & a[r] >= p, set r = r - 1
2.3. if l < r, swap a[l] and a[r]
3. Set a[left] = a[r], a[r] = p
4. Terminate
5
Example of partitioning
8
Partitioning at various levels
9
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?
10
Worst case
• In the worst case, partitioning always divides the
size n array into these three parts:
– A length one part, containing the pivot itself
– A length zero part, and
– A length n-1 part, containing everything else
• We don’t recur on the zero-length part
• Recurring on the length n-1 part requires (in the
worst case) recurring to depth n-1
11
Worst case partitioning
12
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!
13
Typical case for quicksort
14
Tweaking Quicksort
19
The End
20