text: Rearrange Array to find K using Binary Search algorithm without sorting | Function to rearrange the array ; Stores the rearranged array ; Stores whether the arrangement is possible or not ; Update K with the position of K ; Stores all elements lesser than and greater than in vector smaller and greater respectively ; Traverse the array arr [ ] ; If arr [ i ] is less than arr [ K ] ; Else ; Iterate unil low is less than or equal to high ; Stores mid point ; If mid is equal to K ; If mid is less than K ; If mid is greater than K ; If f is - 1 ; Iterate in the range [ 1 , N ] ; If ans [ i ] is equal to - 1 ; Print the rearranged array ; Input ; Function Call
code: function Rearrange ( arr , K , N ) { let ans = new Array ( N + 1 ) ; let f = - 1 ; for ( let i = 0 ; i < N ; i ++ ) { ans [ i ] = - 1 ; } for ( let i = 0 ; i < arr . length ; i ++ ) { if ( arr [ i ] == K ) { K = i ; break ; } } let smaller = [ ] ; let greater = [ ] ; for ( let i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < arr [ K ] ) smaller . push ( arr [ i ] ) ; else if ( arr [ i ] > arr [ K ] ) greater . push ( arr [ i ] ) ; } let low = 0 , high = N - 1 ; while ( low <= high ) { let mid = Math . floor ( ( low + high ) / 2 ) ; if ( mid == K ) { ans [ mid ] = arr [ K ] ; f = 1 ; break ; } else if ( mid < K ) { if ( smaller . length == 0 ) { break ; } ans [ mid ] = smaller [ smaller . length - 1 ] ; smaller . pop ( ) ; low = mid + 1 ; } else { if ( greater . length == 0 ) { break ; } ans [ mid ] = greater [ greater . length - 1 ] ; greater . pop ( ) ; high = mid - 1 ; } } if ( f == - 1 ) { document . write ( - 1 ) ; return ; } for ( let i = 0 ; i < N ; i ++ ) { if ( ans [ i ] == - 1 ) { if ( smaller . length != 0 ) { ans [ i ] = smaller [ smaller . length - 1 ] ; smaller . pop ( ) ; } else if ( greater . length != 0 ) { ans [ i ] = greater [ greater . length - 1 ] ; greater . pop ; } } } for ( let i = 0 ; i < N ; i ++ ) document . write ( ans [ i ] + " " ) ; document . write ( " " ) } let arr = [ 10 , 7 , 2 , 5 , 3 , 8 ] ; let K = 7 ; let N = arr . length ; Rearrange ( arr , K , N ) ;