Complexity and efficiency · 4 / 15 Theory

Efficient searching and sorting

Searching and sorting are the two most repeated tasks in programming, and they are the best showcase for seeing the difference between a slow algorithm and a fast one.

Linear search: O(n)

The elements are walked one by one until the value is found. It works with any list, sorted or not. In the worst case it looks at all the elements.

def linear_search(items, target):
    comparisons = 0
    for i, v in enumerate(items):
        comparisons += 1
        if v == target:
            return i, comparisons
    return -1, comparisons

print(linear_search([4, 8, 15, 16, 23, 42], 23))   # (4, 5)
print(linear_search([4, 8, 15, 16, 23, 42], 5))    # (-1, 6)

You practise it in Linear search counting steps.

Binary search: O(log n)

If the list is sorted, you can look at the middle element and discard half at once: if the value you want is greater, it can only be on the right; if it is smaller, on the left. You repeat with the half that is left.

def binary_search(items, target):
    low, high = 0, len(items) - 1
    comparisons = 0
    while low <= high:
        middle = (low + high) // 2
        comparisons += 1
        if items[middle] == target:
            return middle, comparisons
        if items[middle] < target:
            low = middle + 1
        else:
            high = middle - 1
    return -1, comparisons

data = list(range(0, 2000, 2))   # 1000 sorted even numbers
print(binary_search(data, 1000))   # (500, 9)
print(binary_search(data, 1001))   # (-1, 10)

With 1 000 elements at most 10 comparisons are needed, and with 1 000 000, about 20. Doubling the data only adds one step. You compare both searches in Binary search counting steps.

bisect: binary search already written

The bisect module of the standard library offers binary search, and it also serves to insert while keeping a list sorted.

import bisect

data = [10, 20, 30, 40]
print(bisect.bisect_left(data, 30))   # 2   (position where it is or should be)
print(bisect.bisect_left(data, 35))   # 3

bisect.insort(data, 25)
print(data)                           # [10, 20, 25, 30, 40]

Sorting: what you already have

sorted() and list.sort() use a very optimised algorithm (*Timsort*) with cost O(n log n). It is almost always what you should use. Sorting by hand only makes sense to learn or for very special cases.

A slow sorting algorithm: bubble sort, O(n²)

Bubble sort compares adjacent pairs and swaps them if they are the wrong way round. After each pass, the largest one "bubbles up" to the end.

def bubble(items):
    items = list(items)
    comparisons = 0
    n = len(items)
    for i in range(n - 1):
        for j in range(n - 1 - i):
            comparisons += 1
            if items[j] > items[j + 1]:
                items[j], items[j + 1] = items[j + 1], items[j]
    return items, comparisons

print(bubble([5, 1, 4, 2, 8]))   # ([1, 2, 4, 5, 8], 10)

It always makes n(n−1)/2 comparisons: with 1 000 elements that is almost 500 000, with 1 000 000 it would be about 500 000 000 000. With sorted() it would be about 20 million. Check it in Bubble sort counting steps.

One problem, two solutions: the maximum sum

Finding the largest sum of consecutive elements of a list can be solved by trying all the stretches (O(n²)), or with Kadane's algorithm in a single pass (O(n)): at each position you decide whether it is better to continue the current stretch or start a new one.

def kadane(values):
    current = best = values[0]
    for v in values[1:]:
        current = max(v, current + v)
        best = max(best, current)
    return best

print(kadane([-2, 1, -3, 4, -1, 2, 1, -5, 4]))   # 6

You see it up close in Maximum subarray. The moral is that many problems admit a much better solution if you think a little before going over everything.

Summary

AlgorithmCostRequirement
Linear searchO(n)none
Binary searchO(log n)sorted list
sorted() / sort()O(n log n)none
Bubble sortO(n²)none (only to learn)
KadaneO(n)none