Counting Sort visualization
Count occurrences of each value, then rebuild the array from the counts.
No comparisons at all: for small integer ranges, tally how many times each value appears, then write each value out count times.
Negative numbers are handled by offsetting: value v is counted in slot v − min, so the count array spans exactly min..max.
Runs in O(n + k) where k = max − min + 1 — fantastic for ages, grades or digits, wasteful when k is huge.
Complexity
Time: best O(n + k), average O(n + k), worst O(n + k). Space: O(k). Difficulty: Intermediate.
Pseudocode
procedure countingSort(A):
lo ← min(A); C ← zeros of size max(A) − lo + 1
for x in A: C[x − lo] ← C[x − lo] + 1
k ← 0
for v ← lo to max(A):
repeat C[v − lo] times: A[k] ← v; k ← k + 1More sorting algorithms
- Bubble Sort — Repeatedly swap adjacent out-of-order pairs; the largest value bubbles to the end each pass.
- Selection Sort — Find the minimum of the unsorted part and swap it to the front.
- Insertion Sort — Grow a sorted prefix by inserting each new value into its correct slot.
- Cocktail Shaker Sort — Bubble sort that alternates direction, moving large values right and small values left.
- Shell Sort — Insertion sort over shrinking gaps, so values travel long distances early.
- Merge Sort — Divide in half, sort each half recursively, then merge the two sorted halves.
- Quick Sort — Partition around a pivot so smaller values go left and larger go right, then recurse.
- Heap Sort — Build a max-heap, then repeatedly move the root (maximum) to the end and re-heapify.
- Radix Sort (LSD) — Sort by the ones digit, then tens, then hundreds — each pass is a stable bucket sort.