Divide & Conquer · Merge

Count Inversions Visualizer

What is Count Inversions

An inversion is a pair of indices i < j with a[i] > a[j]. Return how many such pairs exist. Merging two sorted halves counts the cross pairs in linear time: when the right head is smaller, it forms an inversion with every value still waiting on the left.

2 4 1 3 5
3

Approach

An inversion is a pair i < j with a[i] > a[j]. Checking every pair is quadratic. Merge sort already walks those pairs while it merges two sorted halves.

Inside each halfRecursion counts the inversions that sit entirely on the left and entirely on the right.
Across the middleWhen the merge takes the right head, that value is smaller than every value still waiting on the left. Add that remaining count.

Taking the left head adds nothing, because the right half is sorted and the right head is not smaller. The total is the two recursive counts plus the cross count.

Interactive solution

A merge that adds one inversion per remaining left value
def sort_count(a):
if len(a) <= 1: return a, 0
split into left and right
sort and count each half
merge the two sorted halves
taking the left head adds nothing
taking the right head adds every remaining left value
return merged run and the count
Step 0/0 Answer —

The finished picture is on screen when the page opens. Next and Play start again from the first step.

Complexity

PieceCostWhy
TimeO(n log n)The same recursion as merge sort, plus a constant-time add.
MemoryO(n)The merge builds a new run.

Implementation

def sort_count(a):
    if len(a) <= 1:
        return a, 0
    mid = len(a) // 2
    left, c1 = sort_count(a[:mid])
    right, c2 = sort_count(a[mid:])
    out, i, j, cross = [], 0, 0, 0
    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            out.append(left[i]); i += 1
        else:
            out.append(right[j])
            cross += len(left) - i
            j += 1
    out.extend(left[i:]); out.extend(right[j:])
    return out, c1 + c2 + cross