Count inversions in a permutation of first N natural numbers | Python3 program for the above approach ; Function to count number of inversions in a permutation of first N natural numbers ; Store array elements in sorted order ; Store the count of inversions ; Traverse the array ; Store the index of first occurrence of arr [ i ] in vector V ; Add count of smaller elements than current element ; Erase current element from vector and go to next index ; Print the result ; Driver Code ; Given Input ; Function Call
from bisect import bisect_left NEW_LINE def countInversions ( arr , n ) : NEW_LINE INDENT v = [ ] NEW_LINE for i in range ( 1 , n + 1 , 1 ) : NEW_LINE INDENT v . append ( i ) NEW_LINE DEDENT ans = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT itr = bisect_left ( v , arr [ i ] ) NEW_LINE ans += itr NEW_LINE v = v [ : itr ] + v [ itr + 1 : ] NEW_LINE DEDENT print ( ans ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , 3 , 1 , 5 , 4 ] NEW_LINE n = len ( arr ) NEW_LINE countInversions ( arr , n ) NEW_LINE DEDENT