Counting inversions in an array

前端 未结 30 1822
死守一世寂寞
死守一世寂寞 2020-11-22 04:14

I\'m designing an algorithm to do the following: Given array A[1... n], for every i < j, find all inversion pairs such that A[i] > A[j]

30条回答
  •  南笙
    南笙 (楼主)
    2020-11-22 04:42

    Note that the answer by Geoffrey Irving is wrong.

    The number of inversions in an array is half the total distance elements must be moved in order to sort the array. Therefore, it can be computed by sorting the array, maintaining the resulting permutation p[i], and then computing the sum of abs(p[i]-i)/2. This takes O(n log n) time, which is optimal.

    An alternative method is given at http://mathworld.wolfram.com/PermutationInversion.html. This method is equivalent to the sum of max(0, p[i]-i), which is equal to the sum of abs(p[i]-i])/2 since the total distance elements move left is equal to the total distance elements move to the right.

    Take the sequence { 3, 2, 1 } as an example. There are three inversions: (3, 2), (3, 1), (2, 1), so the inversion number is 3. However, according to the quoted method the answer would have been 2.

提交回复
热议问题