Quick Sort
- Pick a pivot element p in the array
- Partition the array into
- Recursively sort the two partitions.
Key benefit: No temporary array!
Pseudocode
def partition(ls, lo, hi):
if lo < hi:
pivot, i, j = ls[(lo + hi) // 2], lo, hi
while True:
while ls[i] < pivot and i < hi:
i += 1
while pivot < ls[j] and j > lo:
j -= 1
if i > j:
break
ls[i], ls[j] = ls[j], ls[i]
i += 1
j -= 1
partition(ls, lo, j)
partition(ls, i, hi)
def quicksort(ls):
partition(ls, 0, len(ls) - 1)
Time Complexity
- Best Case:
- Average Case:
- Worst Case:
Space Complexity
- Worst Case:
Implementation details
- How to pick a pivot?
- Random Element
- Median of three
- Dealing with duplicates? Quicksort doesn’t perform well with lots of duplicate elemnts
CS240
See Partition.