Data Structures & Algorithms · Module 7 · Lesson 11 min read

Sorting Algorithms

The main algorithms

AlgorithmAverageWorstSpaceStableIdea
Bubble sortO(n²)O(n²)O(1)✅swap neighbours
Insertion sortO(n²)O(n²)O(1)✅insert each item into the sorted part; fast for nearly sorted data
Merge sortO(n log n)O(n log n)O(n)✅split, sort halves, merge
Quick sortO(n log n)O(n²)O(log n)❌partition around a pivot
Heap sortO(n log n)O(n log n)O(1)❌repeatedly take the max from a heap
Counting sortO(n + k)O(n + k)O(k)✅for small integer ranges

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

Divide and conquer

Merge sort splits the list in half until single items remain, then merges sorted halves. log n levels × n work per level = O(n log n).

In real code

Use sorted(items) or items.sort(). Python uses Timsort (merge + insertion), which is stable and very fast on real data.

Python
sorted(people, key=lambda p: (p.age, p.name))   # by age, then name
sorted(nums, reverse=True)

Lower bound

Comparison-based sorting can't beat O(n log n) in general. Counting and radix sort are faster only because they don't compare items.

Example

Python
def insertion_sort(a):
    a = 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] = key
    return a

def merge_sort(a):
    if len(a) <= 1:
        return a
    mid = len(a) // 2
    left, right = merge_sort(a[:mid]), merge_sort(a[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(a):
    if len(a) <= 1:
        return a
    pivot = a[len(a) // 2]
    return (quick_sort([x for x in a if x < pivot])
            + [x for x in a if x == pivot]
            + quick_sort([x for x in a if x > pivot]))

data = [38, 27, 43, 3, 9, 82, 10]
print(insertion_sort(data))   # [3, 9, 10, 27, 38, 43, 82]
print(merge_sort(data))       # same
print(quick_sort(data))       # same

students = [("Ana", 90), ("Ben", 85), ("Cara", 90)]
print(sorted(students, key=lambda s: (-s[1], s[0])))
# [('Ana', 90), ('Cara', 90), ('Ben', 85)]