Algorithms · Visualized
Sorting Algorithms
Sorting Algorithms
Seventeen sorting algorithms on the same shuffled data — watch comparisons, swaps, pivots and heaps rearrange bars step by step.
Big-O: Best O(n log n) comparison sorts; counting/radix/bucket reach O(n + k) on small integer keys.
Sorting Algorithms
Rearranging data into order — the foundation most other algorithms build on.
A sorting algorithm rearranges the elements of a list so they follow a chosen order, usually ascending numeric order or lexicographic order. Sorting is worth studying on its own because so many other problems become easy once the data is ordered: binary search, deduplication, median-finding, interval merging and database indexes all lean on sorted data.
The general recipe
- Fix the comparison: what does "a comes before b" mean (numbers, strings, custom keys)?
- Pick a strategy: exchange (bubble), selection, insertion, merging, partitioning (quick), or counting-based placement.
- Watch the invariants: after pass k, the first k items are final (bubble/selection), or a growing prefix is always sorted (insertion).
- Measure the cost: count comparisons and swaps, and track extra memory used.
- Validate edge inputs: empty array, single element, all-equal keys, already sorted, reverse sorted.
Vocabulary you'll meet everywhere here
- Stability
- equal keys keep their original relative order (stable: merge, insertion, counting; unstable: quick, heap, selection)
- In-place
- uses only O(1) extra space beyond the input (heap, bubble, insertion) versus O(n) (merge)
- Comparison sort
- only asks "is a < b?" — provably needs Ω(n log n) comparisons in the worst case
- Non-comparison sort
- uses the structure of integer keys to beat that bound — counting and radix run in O(n + k)
- Adaptive
- runs faster on nearly-sorted input; insertion sort is O(n) on already-sorted data
Where this family shows up
- Preprocessing for binary search, deduplication and interval algorithms
- Databases and spreadsheets ordering rows by one or more keys
- Median and percentile statistics, load balancing, ranking and leaderboards
Common pitfalls
- Naive quicksort degenerates to O(n²) on already-sorted or reverse-sorted input — use random or median-of-three pivots
- Counting/radix sort only apply when keys are integers in a modest range; they are not general comparison sorts
- Assuming stability: switching from merge sort to heap sort silently reorders equal keys
- Deep recursion in quicksort on adversarial input can overflow the call stack — recurse on the smaller half first
def bubble_sort(a):
n = len(a)
for i in range(n - 1):
swapped = False
for j in range(n - 1 - i):
if a[j] > a[j + 1]:
a[j], a[j + 1] = a[j + 1], a[j]
swapped = True
if not swapped:
break
return aRecommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.