I am reading Algorithm Introduction, Second Edition. He has an exercise, problem 2.4
Let A [1 n] be an array of n different numbers. If I <j and A [i]> A [j], then the pair (i, j) is called the inversion of A.
e. Give an algorithm that determines the number of inversions in any permutation of n elements in the Ξ (n lg n) worst case. (Hint: change the merge sort.)
Then I found this solution in the Instructor's Guide
COUNT-INVERSIONS ( A, p, r) inversions β 0 if p < r then q β ( p + r)/2 inversions β inversions +C OUNT-I NVERSIONS ( A, p, q) inversions β inversions +C OUNT-I NVERSIONS ( A, q + 1, r) inversions β inversions +M ERGE -I NVERSIONS ( A, p, q, r) return inversions MERGE -INVERSIONS ( A, p, q, r) n1 β q β p + 1 n2 β r β q create arrays L[1 . . n1 + 1] and R[1 . . n2 + 1] for i β 1 to n1 do L[i] β A[ p + i β 1] for j β 1 to n2 do R[ j ] β A[q + j ] L[n 1 + 1] β β R[n 2 + 1] β β i β1 j β1 inversions β 0 counted β FALSE for k β p to r do if counted = FALSE and R[ j ] < L[i] then inversions β inversions +n1 β i + 1 counted β TRUE if L[i] β€ R[ j ] then A[k] β L[i] i βi +1 else A[k] β R[ j ] j β j +1 counted β FALSE return inversions
My question is: I found that the variable is considered really useless. In the first case, if can be set to TRUE , but this means that R [J] L [i], so in the last sentence it will be set to FALSE .
Can someone give me an example that could explain why counting is needed?
source share