Count inversions in an array | Set 3 ( Using BIT ) | Python3 program to count inversions using Binary Indexed Tree ; Returns sum of arr [ 0. . index ] . This function assumes that the array is preprocessed and partial sums of array elements are stored in BITree . ; Traverse ancestors of BITree [ index ] ; Add current element of BITree to sum ; Move index to parent node in getSum View ; Updates a node in Binary Index Tree ( BITree ) at given index in BITree . The given value ' val ' is added to BITree [ i ] and all of its ancestors in tree . ; Traverse all ancestors and add 'val ; Add ' val ' to current node of BI Tree ; Update index to that of parent in update View ; Converts an array to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , 7 , - 90 , 100 , 1 is converted to 3 , 1 , 4 , 2 ; Create a copy of arrp in temp and sort the temp array in increasing order ; Traverse all array elements ; lower_bound ( ) Returns pointer to the first element greater than or equal to arr [ i ] ; Returns inversion count arr [ 0. . n - 1 ] ; Convert arr to an array with values from 1 to n and relative order of smaller and greater elements remains same . For example , 7 , - 90 , 100 , 1 is converted to 3 , 1 , 4 , 2 ; Create a BIT with size equal to maxElement + 1 ( Extra one is used so that elements can be directly be used as index ) ; Traverse all elements from right . ; Get count of elements smaller than arr [ i ] ; Add current element to BIT ; Driver program
from bisect import bisect_left as lower_bound NEW_LINE def getSum ( BITree , index ) : NEW_LINE INDENT while ( index > 0 ) : NEW_LINE INDENT sum += BITree [ index ] NEW_LINE index -= index & ( - index ) NEW_LINE DEDENT return sum NEW_LINE DEDENT def updateBIT ( BITree , n , index , val ) : NEW_LINE ' NEW_LINE INDENT while ( index <= n ) : NEW_LINE INDENT BITree [ index ] += val NEW_LINE DEDENT index += index & ( - index ) NEW_LINE DEDENT def convert ( arr , n ) : NEW_LINE INDENT temp = [ 0 ] * ( n ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT temp [ i ] = arr [ i ] NEW_LINE DEDENT temp = sorted ( temp ) NEW_LINE for i in range ( n ) : NEW_LINE INDENT arr [ i ] = lower_bound ( temp , arr [ i ] ) + 1 NEW_LINE DEDENT DEDENT def getInvCount ( arr , n ) : NEW_LINE INDENT convert ( arr , n ) NEW_LINE BIT = [ 0 ] * ( n + 1 ) NEW_LINE for i in range ( n - 1 , - 1 , - 1 ) : NEW_LINE INDENT invcount += getSum ( BIT , arr [ i ] - 1 ) NEW_LINE updateBIT ( BIT , n , arr [ i ] , 1 ) NEW_LINE DEDENT return invcount NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 8 , 4 , 2 , 1 ] NEW_LINE n = len ( arr ) NEW_LINE print ( " Number ▁ of ▁ inversions ▁ are ▁ : ▁ " , getInvCount ( arr , n ) ) NEW_LINE DEDENT