Convert an array to reduced form | Set 3 ( Binary Search ) | Function to find the reduced form of the given array arr [ ] ; Stores the sorted form of the the given array arr [ ] ; Sort the array brr [ ] ; Traverse the given array arr [ ] ; Perform the Binary Search ; Calculate the value of mid ; Print the current index and break ; Update the value of l ; Update the value of r ; Driver Code
function convert ( arr , n ) { var brr = Array ( n ) . fill ( 0 ) ; var i ; for ( i = 0 ; i < n ; i ++ ) brr [ i ] = arr [ i ] ; brr . sort ( ) ; for ( i = 0 ; i < n ; i ++ ) { var l = 0 , r = n - 1 , mid ; while ( l <= r ) { mid = parseInt ( ( l + r ) / 2 , 10 ) ; if ( brr [ mid ] == arr [ i ] ) { document . write ( mid + ' ' ) ; break ; } else if ( brr [ mid ] < arr [ i ] ) { l = mid + 1 ; } else { r = mid - 1 ; } } } } var arr = [ 10 , 20 , 15 , 12 , 11 , 50 ] ; var N = arr . length ; convert ( arr , N ) ;