Problem: Let $ A $ be an array of $ n $ different elements from an ordered interval.
Let $ I(A) $ be the number of inversions in array $A$, meaning, the number of pairs of indexes $ 0 \leq i < j <n $ for which it occurs that $ A[i] > A[j] $. Notice that $ 0 \leq I(A) \leq
{n \choose{} 2} $ and that $ I(A) = 0 $ if and only if $ A $ is sorted.
Prove that given array $A$, it is possible to calculate $ I(A) $ in time $ O(n \log n) $.
Official answer to problem: Put the elements one by one into an AVL Finger Tree with a pointer to minimal key in the tree. After each insertion calculate $ n - TreeRank(x) $ , where $ n $ is the current number of elements after insertion and $ x $ is the node we inserted. Return the sum of these numbers.
Note: $ TreeRank(x) $ = position of $ x $ in sorted order in $ A $ ( count starts from 1 and not 0 , for example if $ A = [ 6, 5 ,8 ] $ and $ N_b , N_a $ are nodes whose keys are 6 and 5 respectively then $ TreeRank(N_b) = 2 , TreeRank(N_a) = 1 $ ).
My question: I don't understand why calculating $ n - TreeRank(x) $ each time we insert $ x $ and then summing this result, will end up giving me the total number of inversions as we put each element of the array into the tree. What's the reasoning behind this technique that it works? Can you please help to elucidate this?
Thanks in advance for any help!