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]
Another Python solution, short one. Makes use of builtin bisect module, which provides functions to insert element into its place in sorted array and to find index of element in sorted array.
The idea is to store elements left of n-th in such array, which would allow us to easily find the number of them greater than n-th.
import bisect
def solution(A):
sorted_left = []
res = 0
for i in xrange(1, len(A)):
bisect.insort_left(sorted_left, A[i-1])
# i is also the length of sorted_left
res += (i - bisect.bisect(sorted_left, A[i]))
return res