Cohort 4Register

PART 4 · DSA AND COMPLEXITY · CHAPTER 24

Sorting: what Python does, and when to sort yourself

FreeLesson 49 of 78

You will almost never write a sort at work, but interviews ask how sorting works, what it costs, and when sorting first makes a problem easy.

MERGE SORT AND COUNTING SORTPYTHON 3.12
def merge_sort(xs):                    # O(n log n) time, O(n) space
    if len(xs) <= 1:
        return xs
    mid = len(xs) // 2
    left, right = merge_sort(xs[:mid]), merge_sort(xs[mid:])
    out, i, j = [], 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:          # <= keeps it stable
            out.append(left[i]); i += 1
        else:
            out.append(right[j]); j += 1
    return out + left[i:] + right[j:]

def counting_sort(xs, max_val):        # O(n + k) for small integers
    counts = [0] * (max_val + 1)
    for x in xs:
        counts[x] += 1
    return [v for v, c in enumerate(counts) for _ in range(c)]

print(merge_sort([1999, 747, 3498, 796, 1348]))
print(counting_sort([3, 1, 2, 3, 0, 2, 1], 3))

Output

[747, 796, 1348, 1999, 3498]
[0, 1, 1, 2, 2, 3, 3]
AlgorithmTime (typical)Extra spaceStableKnow it for
Timsort (Python sorted, list.sort)O(n log n), O(n) if nearly sortedUp to O(n)YesWhat you actually use
Merge sortO(n log n) alwaysO(n)YesExternal sort of huge files
Quick sortO(n log n), O(n²) worstO(log n)NoIn-place sorting, quickselect
Heap sortO(n log n)O(1)NoHeaps (page 55)
Counting / bucket sortO(n + k)O(k)YesSmall integer keys, top-k by frequency
A CUSTOM COMPARISON: ARRANGE NUMBERS INTO THE LARGEST NUMBERPYTHON 3.12
from functools import cmp_to_key

def largest_number(nums):
    strs = [str(n) for n in nums]
    def order(a, b):                    # which pair reads bigger?
        return -1 if a + b > b + a else (1 if a + b < b + a else 0)
    strs.sort(key=cmp_to_key(order))
    out = "".join(strs)
    return "0" if out[0] == "0" else out

print(largest_number([3, 30, 34, 5, 9]), largest_number([0, 0]))

Output

9534330 0

Some orders are easier to write as "is a before b?" than as a key. cmp_to_key turns that comparison into a key. Still O(n log n) comparisons, each costing the length of the strings.

Practice before you move on

  1. Sort the amounts of orders.csv with your own merge sort and compare the result with sorted().
  2. Use counting sort on the customer_id column of orders.csv.