Divide & Conquer · Sorting

Quick Sort Visualizer

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.

Pivot and boundaryThe picture uses the last value as the pivot. Index i is the next slot for a value that belongs on the left.
ScanIndex j walks the range. A value at most the pivot swaps with i and i moves forward. At the end the pivot swaps into i.

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

Pivot, boundary i, and the scan j
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: swap a[i], a[j]; i += 1
else: leave a[j] on the large side
swap a[i], a[hi]
sort left of i, then right of i
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
AverageO(n log n)Balanced pivots cut the range in half.
Worst caseO(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)