Counting inversions in an array

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

    Solution One.Work well when there is a large amount of numbers

    def countInversions(arr):
     n = len(arr)
     if n == 1:
        return 0
     n1 = n // 2
     n2 = n - n1
     arr1 = arr[:n1]
     arr2 = arr[n1:]
     # print(n1,'||',n1,'||',arr1,'||',arr2)
     ans = countInversions(arr1) + countInversions(arr2)
     print(ans)
     i1 = 0
     i2 = 0
     for i in range(n):
         # print(i1,n1,i2,n2)
         if i1 < n1 and (i2 >= n2 or arr1[i1] <= arr2[i2]):
             arr[i] = arr1[i1]
             ans += i2
             i1 += 1
         elif i2 < n2:
             arr[i] = arr2[i2]
             i2 += 1
     return ans
    

    Solution Two.Simple solution.

    def countInversions(arr):
          count = 0
          for i in range(len(arr)):
              for j in range(i, len(arr)):
                   # print(arr[i:len(arr)])
                     if arr[i] > arr[j]:
                         print(arr[i], arr[j])
                         count += 1
          print(count)
    

提交回复
热议问题