Count inversions in a permutation of first N natural numbers | Java 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
import java . util . Vector ; class GFG { static void countInversions ( int arr [ ] , int n ) { Vector < Integer > v = new Vector < > ( ) ; for ( int i = 1 ; i <= n ; i ++ ) { v . add ( i ) ; } int ans = 0 ; for ( int i = 0 ; i < n ; i ++ ) { int itr = v . indexOf ( arr [ i ] ) ; ans += itr ; v . remove ( itr ) ; } System . out . println ( ans ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 1 , 5 , 4 } ; int n = arr . length ; countInversions ( arr , n ) ; } }