Probability of obtaining pairs from two arrays such that element from the first array is smaller than that of the second array | Function to find probability such that x < y and X belongs to arr1 [ ] & Y belongs to arr2 [ ] ; Stores the length of arr1 ; Stores the length of arr2 ; Stores the result ; Sort the arr2 [ ] in the ascending order ; Traverse the arr1 [ ] ; Stores the count of elements in arr2 that are greater than arr [ i ] ; Increment res by y ; Update the resultant probability ; Return the result ; Function to return the count of elements from the array which are greater than k ; Stores the index of the leftmost element from the array which is at least k ; Finds number of elements greater than k ; If mid element is at least K , then update the value of leftGreater and r ; Update leftGreater ; Update r ; If mid element is at most K , then update the value of l ; Return the count of elements greater than k ; Driver Code
function probability ( arr1 , arr2 ) { var N = 4 ; var M = 4 ; var res = 0 ; arr2 . sort ( function ( a , b ) { return a - b ; } ) ; for ( var i = 0 ; i < N ; i ++ ) { var y = countGreater ( arr2 , arr1 [ i ] ) ; res += y ; } res = res / ( N * M ) ; return res ; } function countGreater ( arr , k ) { var n = 4 ; var l = 0 ; var r = n - 1 ; var leftGreater = n ; while ( l <= r ) { var m = Math . floor ( l + ( r - l ) / 2 ) ; if ( arr [ m ] > k ) { leftGreater = m ; r = m - 1 ; } else l = m + 1 ; } return n - leftGreater ; } var arr1 = [ 5 , 2 , 6 , 1 ] ; var arr2 = [ 1 , 6 , 10 , 1 ] ; document . write ( probability ( arr1 , arr2 ) ) ;