Python · Module 12 · Lesson 31 min read

Sorting & Searching Algorithms

Classic sorting algorithms

AlgorithmAverageWorstNotes
Bubble sortO(n²)O(n²)easy to learn, too slow in practice
Insertion sortO(n²)O(n²)fast for small or nearly sorted lists
Merge sortO(n log n)O(n log n)stable, uses extra memory
Quick sortO(n log n)O(n²)fast in practice, in place
TimsortO(n log n)O(n log n)what Python's sorted() uses

Stable means equal items keep their original order, which matters when sorting by several keys.

In real code

Use sorted() / .sort() with key= and reverse=True. Implement algorithms yourself to learn and for interviews.

Searching

  • Unsorted data: linear search, O(n).
  • Sorted data: binary search, O(log n). The bisect module does it for you and can insert while keeping the order.

▶️ Runs in the app.

Example

Python
import bisect

def merge_sort(items):
    if len(items) <= 1:
        return items
    mid = len(items) // 2
    left, right = merge_sort(items[:mid]), merge_sort(items[mid:])
    merged, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            merged.append(left[i]); i += 1
        else:
            merged.append(right[j]); j += 1
    return merged + left[i:] + right[j:]

def quick_sort(items):
    if len(items) <= 1:
        return items
    pivot = items[len(items) // 2]
    return (quick_sort([x for x in items if x < pivot])
            + [x for x in items if x == pivot]
            + quick_sort([x for x in items if x > pivot]))

data = [5, 2, 9, 1, 5, 6]
print(merge_sort(data))     # [1, 2, 5, 5, 6, 9]
print(quick_sort(data))     # [1, 2, 5, 5, 6, 9]

students = [("Ana", 90), ("Ben", 72), ("Cara", 90)]
print(sorted(students, key=lambda s: (-s[1], s[0])))   # by score, then name

scores = [10, 20, 30, 40]
print(bisect.bisect_left(scores, 30))   # 2
bisect.insort(scores, 25)
print(scores)                           # [10, 20, 25, 30, 40]