Mergesort Inversion Count (Python)
Count inversions in a list using a modified mergesort that counts crossings during the merge step.
Code
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
Fuzzy Match TesterTest subsequence fuzzy matching: check whether pattern characters appear in order inside a text, with positions and highlighting.Levenshtein Distance CalculatorCompute the classic edit distance between two strings with a space-optimized DP and a normalized similarity percentage.Soundex EncoderEncode names into classic American Soundex codes with NARA rules for H/W separators, vowel boundaries, and zero padding.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.