Classic algorithms · 6 / 22 Theory

Linear algorithms: counting, quickselect and Boyer-Moore

You do not always need to sort. Three classic algorithms solve with a single pass (or almost) problems that seem to ask for sorting.

Counting sort

If the values are integers in a small range, you count how many times each one appears and rebuild the list. It does not compare elements, so it is not subject to the n log n limit: it costs O(n + k), with k the size of the range.

numbers = [3, 1, 3, 0, 1, 3]
counts = [0] * 4                  # los valuees están entre 0 y 3
for x in numbers:
    counts[x] += 1
print(counts)                     # [1, 2, 0, 3]

ordered = []
for value, times in enumerate(counts):
    ordered.extend([value] * times)
print(ordered)                  # [0, 1, 1, 3, 3, 3]

It only works with small ranges (a list of 10 numbers between 0 and a billion does not need a counter with a billion positions). You practice it in Counting sort.

Quickselect

For the k-th smallest or the median you do not need to sort everything. You split into smaller, equal and larger than a pivot, as in quicksort, but you only continue with the group where the answer falls. On average it costs O(n).

def select(items, k):         # k-th smallest, k starts at 1
    pivot = items[0]
    smaller = [x for x in items if x < pivot]
    equal = [x for x in items if x == pivot]
    larger = [x for x in items if x > pivot]
    if k <= len(smaller):
        return select(smaller, k)
    if k <= len(smaller) + len(equal):
        return pivot
    return select(larger, k - len(smaller) - len(equal))

print(select([7, 2, 9, 4, 5], 3))    # 5  (the median)

You practice it in The k-th smallest.

Majority element: Boyer-Moore

To know whether a value appears in more than half of the positions, keep a candidate and a counter: a value equal to the candidate reinforces it, a different one weakens it and, if the counter reaches 0, the candidate is changed. If there is a majority, it survives. It goes through the list only once and with constant memory; afterwards you check that it really is one.

def majority(numbers):
    candidate, count = None, 0
    for x in numbers:
        if count == 0:
            candidate, count = x, 1
        elif x == candidate:
            count += 1
        else:
            count -= 1
    return candidate if numbers.count(candidate) > len(numbers) // 2 else None

print(majority([2, 2, 1, 1, 2, 2, 3]))    # 2
print(majority([1, 2, 3]))                # None

You practice it in Majority element. And checking whether two lists have the same elements, without sorting, is counting: Are they permutations of each other?

  • Before sorting, ask yourself whether you really need the sorted list or just one piece of data (the largest, the median, the most frequent).
  • Counting with a dictionary or a list of counters is usually cheaper than sorting.
  • A linear algorithm needs to read all the data at least once: it is the minimum possible.