Skip to main content

Searching and Sorting

Works on sorted data and halves the search space each step: O(log n).

binary_search.py
def binary_search(nums, target):
lo, hi = 0, len(nums) - 1
while lo <= hi:
mid = (lo + hi) // 2
if nums[mid] == target:
return mid
if nums[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1

The standard library has bisect.bisect_left for the same idea.

Sorting algorithms​

AlgorithmBestAverageWorstSpaceStable
Bubble sortO(n)O(n²)O(n²)O(1)Yes
Insertion sortO(n)O(n²)O(n²)O(1)Yes
Merge sortO(n log n)O(n log n)O(n log n)O(n)Yes
Quick sortO(n log n)O(n log n)O(n²)O(log n)No
Heap sortO(n log n)O(n log n)O(n log n)O(1)No

Merge sort​

merge_sort.py
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]:
out.append(left[i]); i += 1
else:
out.append(right[j]); j += 1
return out + left[i:] + right[j:]

In practice​

Use the built-in sorted() / list.sort() (Timsort, O(n log n), stable) and pass key= for custom ordering.