Count inversions in a permutation of first N natural numbers | 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 ; Given Input ; Function Call
function countInversions ( arr , n ) { var v = [ ] ; var i ; for ( i = 1 ; i <= n ; i ++ ) { v . push ( i ) ; } var ans = 0 ; for ( i = 0 ; i < n ; i ++ ) { var index = v . indexOf ( arr [ i ] ) ; ans += index ; v . splice ( index , 1 ) ; } document . write ( ans ) ; } var arr = [ 2 , 3 , 1 , 5 , 4 ] ; var n = arr . length ; countInversions ( arr , n ) ;