Counting inversions in an array

前端 未结 30 1995
死守一世寂寞
死守一世寂寞 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条回答
  •  梦毁少年i
    2020-11-22 04:42

    My answer in Python:

    1- Sort the Array first and make a copy of it. In my program, B represents the sorted array. 2- Iterate over the original array (unsorted), and find the index of that element on the sorted list. Also note down the index of the element. 3- Make sure the element doesn't have any duplicates, if it has then you need to change the value of your index by -1. The while condition in my program is exactly doing that. 4- Keep counting the inversion that will your index value, and remove the element once you have calculated its inversion.

    def binarySearch(alist, item):
        first = 0
        last = len(alist) - 1
        found = False
    
        while first <= last and not found:
            midpoint = (first + last)//2
            if alist[midpoint] == item:
                return midpoint
            else:
                if item < alist[midpoint]:
                    last = midpoint - 1
                else:
                    first = midpoint + 1
    
    def solution(A):
    
        B = list(A)
        B.sort()
        inversion_count = 0
        for i in range(len(A)):
            j = binarySearch(B, A[i])
            while B[j] == B[j - 1]:
                if j < 1:
                    break
                j -= 1
    
            inversion_count += j
            B.pop(j)
    
        if inversion_count > 1000000000:
            return -1
        else:
            return inversion_count
    
    print solution([4, 10, 11, 1, 3, 9, 10])
    

提交回复
热议问题