DSA/Lesson 9 of 11/7 min read
Sorting and Searching
Comparison and non-comparison sorts, stability, merge sort, quick sort, counting and radix sort, binary search and its variants.
On this page
Sorting Algorithm overview
| Algorithm | Best | Average | Worst | Space | Stable |
|---|---|---|---|---|---|
| Bubble | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Selection | O(n^2) | O(n^2) | O(n^2) | O(1) | No |
| Insertion | O(n) | O(n^2) | O(n^2) | O(1) | Yes |
| Merge | O(n log n) | O(n log n) | O(n log n) | O(n) | Yes |
| Quick | O(n log n) | O(n log n) | O(n^2) | O(log n) | No |
| Heap | O(n log n) | O(n log n) | O(n log n) | O(1) | No |
| Counting | O(n + k) | O(n + k) | O(n + k) | O(k) | Yes |
| Radix | O(d(n + b)) | O(d(n + b)) | O(d(n + b)) | O(n + b) | Yes |
Any comparison-based sort needs Omega(n log n) comparisons in the worst case: a decision tree must have n! leaves, so its height is at least log(n!) = Theta(n log n).
Stable Sort
A sort is stable if equal elements keep their original relative order. It matters when sorting by multiple keys: sort by name, then stable sort by age, and people of the same age stay sorted by name.
Python sorted (Timsort) and Java Arrays.sort for objects are stable. Java Arrays.sort for primitives uses dual-pivot quicksort, which is not.
Simple quadratic sorts
Bubble Sort
Repeatedly swap adjacent out-of-order pairs. After pass i, the largest i elements are in place. Stop early if a pass makes no swaps (best case O(n)).
Selection Sort
Find the minimum of the unsorted part and swap it to the front. Always O(n^2) comparisons but only O(n) swaps, useful when writes are expensive.
Insertion Sort
Grow a sorted prefix by inserting each new element into place.
def insertion_sort(a):
for i in range(1, len(a)):
key, j = a[i], i - 1
while j >= 0 and a[j] > key:
a[j + 1] = a[j]
j -= 1
a[j + 1] = keyFast on small or nearly sorted arrays, which is why Timsort and introsort use it for small runs.
Merge Sort
Divide and conquer: split in half, sort each half, merge.
def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]: # <= keeps it stable
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]T(n) = 2T(n/2) + O(n) = O(n log n) always. Needs O(n) extra space. Preferred for linked lists (no random access needed) and for external sorting of data larger than memory.
Bonus: counting inversions is a merge sort with a counter in the merge step.
Quick Sort
Pick a pivot, partition so smaller elements go left and larger go right, recurse on both sides.
def quick_sort(a, lo, hi):
if lo >= hi:
return
pivot, i = a[hi], lo
for j in range(lo, hi): # Lomuto partition
if a[j] < pivot:
a[i], a[j] = a[j], a[i]
i += 1
a[i], a[hi] = a[hi], a[i]
quick_sort(a, lo, i - 1)
quick_sort(a, i + 1, hi)- Average
O(n log n), in place, very cache friendly, usually the fastest in practice. - Worst case
O(n^2)when the pivot is always the min or max (for example, sorted input with last-element pivot). - Fixes: random pivot, median-of-three, and three-way partitioning for many duplicates.
| Merge sort | Quick sort | |
|---|---|---|
| Worst case | O(n log n) | O(n^2) |
| Extra space | O(n) | O(log n) stack |
| Stable | Yes | No |
| Cache behavior | Good | Better |
Quickselect
Find the k-th smallest element by partitioning and recursing into only one side. Average O(n), worst O(n^2); median of medians guarantees O(n).
Non-comparison sorts
Counting Sort
For integers in a small range [0, k]: count occurrences, compute prefix sums for positions, then place elements (iterate backwards to stay stable). O(n + k).
Radix Sort
Sort by each digit from least significant to most, using a stable counting sort per digit. O(d * (n + b)) for d digits in base b. Good for fixed-width integers and strings.
Bucket sort: scatter uniformly distributed floats into n buckets, sort each, concatenate. O(n) average.
Binary Search
Search a sorted (or monotonic) space by halving it each step. O(log n).
def binary_search(a, target):
lo, hi = 0, len(a) - 1
while lo <= hi:
mid = lo + (hi - lo) // 2 # avoids overflow in fixed-width ints
if a[mid] == target:
return mid
if a[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1Lower bound and upper bound
- Lower bound: first index with
a[i] >= x. - Upper bound: first index with
a[i] > x.
Count of x = upper bound minus lower bound. Python has bisect_left and bisect_right.
Common variants
| Problem | Trick |
|---|---|
| Search in rotated sorted array | One half is always sorted; check if the target is in it |
| Find minimum in rotated array | Compare a[mid] with a[hi] |
| Peak element | Move toward the larger neighbor |
| First and last position | Lower and upper bound |
| Search a 2D sorted matrix | Treat as a flat array of m * n |
| Median of two sorted arrays | Binary search the partition, O(log min(m, n)) |
Binary Search on Answer
When the answer is a number and feasibility is monotonic (if x works, every larger x works), binary search over the answer and test each candidate with a greedy check.
Examples: Koko eating bananas, ship packages within D days, split array largest sum, aggressive cows, minimum time to finish jobs.
lo, hi = min_possible, max_possible
while lo < hi:
mid = (lo + hi) // 2
if feasible(mid):
hi = mid
else:
lo = mid + 1
return loPitfalls: infinite loops from lo = mid with mid = (lo + hi) // 2; use (lo + hi + 1) // 2 when moving lo = mid. Decide upfront whether the interval is closed or half-open, and stick to it.
Quick revision
- Comparison sorts are
Omega(n log n); counting and radix sort beat it for bounded integers. - Stable: insertion, merge, counting, radix, Timsort. Not stable: selection, quick, heap.
- Merge sort: guaranteed
O(n log n),O(n)space, good for linked lists and external sorting. - Quick sort: fastest in practice,
O(n^2)worst; randomize the pivot. - Insertion sort is best for small or nearly sorted inputs.
- Binary search needs a monotonic condition; use
lo + (hi - lo) // 2. - Binary search on answer: monotonic feasibility plus a greedy check.