Sorting
Bubble Sort
Repeatedly compares adjacent values and swaps inverted pairs until the largest unsettled value bubbles to the end.
O(n^2) time / O(1) space
- Scan neighboring pairs.
- Swap when the left value is larger.
- Shrink the unsorted suffix after each pass.
Insertion Sort
Builds a sorted prefix by shifting larger values right and inserting the current value into its correct place.
O(n^2) time / O(1) space
- Pick the next unsorted value.
- Shift larger prefix values right.
- Insert the value into the gap.
Selection Sort
Selects the minimum value from the unsorted suffix and places it at the next sorted position.
O(n^2) time / O(1) space
- Track the smallest value.
- Scan the remaining suffix.
- Swap the minimum into place.
Merge Sort
Splits the array into halves, sorts each half recursively, and merges sorted runs back together.
O(n log n) time / O(n) space
- Split into halves.
- Sort each half.
- Merge the smaller front values first.
Quick Sort
Partitions values around a pivot so smaller values move left and larger values move right.
Average O(n log n), worst O(n^2) time / O(log n) space
- Choose a pivot.
- Partition around it.
- Sort the left and right partitions.
Heap Sort
Turns the array into a max heap, repeatedly extracts the maximum, and restores heap order.
O(n log n) time / O(1) space
- Build a max heap.
- Swap root with the end.
- Heapify the reduced heap.
Shell Sort
Runs insertion-style passes over shrinking gaps so distant disorder is reduced early.
Depends on gap sequence / O(1) space
- Pick a gap.
- Insertion-sort by that gap.
- Shrink the gap until it reaches one.
Counting Sort
Counts occurrences of each value and rebuilds the array from frequencies.
O(n + k) time / O(k) space
- Count each value.
- Walk the frequency table.
- Write values back in order.
Radix Sort
Sorts integers digit by digit using stable buckets from least significant to most significant digit.
O(d(n + b)) time / O(n + b) space
- Bucket by current digit.
- Collect buckets in order.
- Move to the next digit.