Counting inversions in an array

前端 未结 30 2505
死守一世寂寞
死守一世寂寞 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:57

    I wonder why nobody mentioned binary-indexed trees yet. You can use one to maintain prefix sums on the values of your permutation elements. Then you can just proceed from right to left and count for every element the number of elements smaller than it to the right:

    def count_inversions(a):
      res = 0
      counts = [0]*(len(a)+1)
      rank = { v : i+1 for i, v in enumerate(sorted(a)) }
      for x in reversed(a):
        i = rank[x] - 1
        while i:
          res += counts[i]
          i -= i & -i
        i = rank[x]
        while i <= len(a):
          counts[i] += 1
          i += i & -i
      return res
    

    The complexity is O(n log n), and the constant factor is very low.

提交回复
热议问题