07.2

Algorithm Visualizer

Animated bar-chart sorting visualizer · two tabs · run your own Python. back to widgets
$algoviz --tab builtin
>15 built-in sorting algorithms · op-counters · side-by-side compare
mode
algorithms · 15
Quick Sort
Divide & conquer · in-place · pivot partition. The classic.
best O(n log n)avg O(n log n)worst O(n²)space O(log n)stable noin-place yes
Quick Sort
n=40
ops0
compares0
reads0
writes0
swaps0
avgO(n log n)
speed
40
how it works·Quick Sortcomparison

Pick a pivot, then partition the array so values smaller than the pivot land left of it and larger values land right. Recurse on each side. The pivot ends each call in its final sorted position.

We use Lomuto partition with the last element as the pivot — easy to step through visually, but also the variant that's fragile on already-sorted input (every partition is maximally unbalanced and you degenerate to O(n²)). Production implementations harden this with a median-of-three pivot, randomised pivots, and a fall-back to heap sort once recursion goes too deep. That hybrid is called introsort and powers C++'s std::sort, Rust's sort_unstable, and .NET's Array.Sort.

source
Quick Sort · python
def quick_sort(arr, lo=0, hi=None):
    if hi is None:
        hi = len(arr) - 1
    if lo < hi:
        p = partition(arr, lo, hi)
        quick_sort(arr, lo, p - 1)
        quick_sort(arr, p + 1, hi)

def partition(arr, lo, hi):
    pivot = arr[hi]
    i = lo
    for j in range(lo, hi):
        if arr[j] < pivot:
            arr[i], arr[j] = arr[j], arr[i]
            i += 1
    arr[i], arr[hi] = arr[hi], arr[i]
    return i
navigate