Sorting

Sorting

Comparison sorts, linear-time sorts and the hybrids used in practice.

Bubble Sort
▶ viz

Repeatedly swap adjacent out-of-order pairs so the largest remaining element bubbles to the end each pass.

O(n²) · O(1) space
Selection Sort
▶ viz

Repeatedly select the minimum of the unsorted suffix and swap it into place; exactly n−1 swaps.

O(n²) · O(1) space
Insertion Sort
▶ viz

Build a sorted prefix by inserting each new element into its correct place among the ones before it.

O(n²) · O(1) space
Merge Sort
▶ viz

Split the array in half, sort each half recursively, then merge the two sorted halves in linear time.

O(n log n) · O(n) space
Quick Sort
▶ viz

Pick a pivot, partition elements into smaller and larger sides, and recursively sort each side.

O(n²) · O(log n) space
Heap Sort
▶ viz

Build a max-heap in place, then repeatedly swap the root to the end and restore the heap.

O(n log n) · O(1) space
Counting Sort
▶ viz

Count occurrences of each key in a small integer range, then place elements by prefix sums — linear time, no comparisons.

O(n + k) · O(n + k) space
Radix Sort
▶ viz

Sort integers digit by digit from least significant to most, using a stable counting sort per digit.

O(d·(n + b)) · O(n + b) space
Bucket Sort
▶ viz

Distribute elements into buckets by value range, sort each bucket, and concatenate — linear on uniform data.

O(n²) · O(n + k) space
Shell Sort
▶ viz

Insertion sort over elements h apart with a shrinking gap sequence, finishing with a plain insertion sort.

O(n^1.5) · O(1) space
TimSort
▶ viz

Adaptive, stable hybrid of merge sort and insertion sort that exploits existing sorted runs; the default sort in Python and Java.

O(n log n) · O(n) space