Count Inversions of size three in a given array | returns count of inversion of size 3 ; initialize result ; count all smaller elements on right of arr [ i ] ; count all greater elements on left of arr [ i ] ; update inversion count by adding all inversions that have arr [ i ] as middle of three elements ; driver program to test above function
function getInvCount ( arr , n ) { let invcount = 0 ; for ( let i = 0 ; i < n - 1 ; i ++ ) { let small = 0 ; for ( let j = i + 1 ; j < n ; j ++ ) if ( arr [ i ] > arr [ j ] ) small ++ ; let great = 0 ; for ( let j = i - 1 ; j >= 0 ; j -- ) if ( arr [ i ] < arr [ j ] ) great ++ ; invcount += great * small ; } return invcount ; } let arr = [ 8 , 4 , 2 , 1 ] ; let n = arr . length ; document . write ( " " + getInvCount ( arr , n ) ) ;