Mergesort Inversion Count (Python)

Count inversions in a list using a modified mergesort that counts crossings during the merge step.

PythonData Integrity

Code

pythonsnippet
26 lines
def count_inversions(arr):
    tmp = [0] * len(arr)

    def merge(lo, mid, hi):
        i, j, k, inv = lo, mid, lo, 0
        for x in range(lo, hi + 1):
            tmp[x] = arr[x]
        while i < mid and j <= hi:
            if tmp[i] <= tmp[j]:
                arr[k] = tmp[i]; i += 1
            else:
                arr[k] = tmp[j]; j += 1; inv += mid - i
            k += 1
        while i < mid:
            arr[k] = tmp[i]; i += 1; k += 1
        while j <= hi:
            arr[k] = tmp[j]; j += 1; k += 1
        return inv

    def sort(lo, hi):
        if lo >= hi:
            return 0
        mid = (lo + hi + 1) // 2
        return sort(lo, mid - 1) + sort(mid, hi) + merge(lo, mid, hi)

    return sort(0, len(arr) - 1)

What the code does

One way to read it: the functions count_inversions, merge and sort, doing all the work.

Repetition is confined to for x in range(lo, hi + 1) — the rest of the file is straight-line.

Applying it

The primary signature is def count_inversions(arr)

The surface worth importing is count_inversions; the helpers around it are private to the snippet.

Statements that matter

def sort(lo, hi):
    if lo >= hi:
        return 0
    mid = (lo + hi + 1) // 2
    return sort(lo, mid - 1) + sort(mid, hi) + merge(lo, mid, hi)

Interactive Tools for This Topic

FAQ

Are there dependencies to manage?
No. There are no dependencies to declare or install. The file defines `count_inversions`, `merge`, `sort` at load time.