Proofs: Counting inversions with a Fenwick tree
These are the human proofs of Counting inversions with a Fenwick tree, at full length.
The Fenwick scan returns the number of inversions full
This proof shows: correctness, termination.
We use the pseudocode of the page, with the input . For let , the number of inversions with right end . Each inversion has exactly one right end, so
Step 1: the ranks preserve order. Line L1 makes , the distinct values of , and line L2 sets where . Such a exists and is unique, because is one of the values and the are distinct. For any , since is strictly increasing in , if and only if , and if and only if . Also .
Step 2: the Fenwick tree lemma. Let be a frequency array, and say that represents when for each . The Fenwick tree page proves, in its file proofs/correctness.md, that if represents , then PREFIX returns for , and that after ADD with the array represents with increased by . Both loops terminate: PREFIX clears one set bit of at each step, so it stops after at most steps, and ADD at least doubles at each step, so exceeds after at most steps.
Step 3: the invariant of the scan. For let . We show that the loop of line L4 keeps:
(S) Before the iteration for : represents , and .
Initialization. Line L3 sets to zeros and . The array is all zeros, and an all-zero represents it, since each is a sum of zeros. The sum is empty. So (S) holds for .
Maintenance. Assume (S) for some . By Step 2, PREFIX returns
where the last equality is Step 1. There are indices , and each has either or , but not both. So $(j - 1) - $ PREFIX, and after line L5, . Line L6 calls ADD with , so by Step 2 the array then represents with increased by 1, which is . So (S) holds for .
Termination. The loop of line L4 runs for and each iteration terminates by Step 2. After the last one, (S) holds for , so , which by (1) is . Line L7 returns it.
The online property. The same invariant shows that after the iteration for , is , which is the inversion count of the prefix , because an inversion of the prefix is an inversion of with .