What is Quick Sort
Pick a pivot and rearrange the range so smaller values sit on its left and larger values sit on its right. Then sort the two sides. The picture uses the last value of the active range as the pivot and draws at most 6 values. Any correct sort passes the practice tests.
10 7 8 9 1 5 1 5 7 8 9 10
Approach
Quick sort picks a pivot and moves every smaller value to its left and every larger value to its right. The pivot is then finished. The same partition runs on each side.
After that swap, the pivot never moves again. If the pivot is always the smallest or largest remaining value, one side is empty and the sort becomes quadratic.
Interactive solution
The finished picture is on screen when the page opens. Next and Play start again from the first step.
Complexity
| Piece | Cost | Why |
|---|---|---|
| Average | O(n log n) | Balanced pivots cut the range in half. |
| Worst case | O(n^2) | Every partition is lopsided. A large random test rejects that case. |
Implementation
def quick_sort(a, lo, hi):
if lo >= hi:
return
pivot = a[hi]
i = lo
for j in range(lo, hi):
if a[j] <= pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)