text: Rearrange Array to find K using Binary Search algorithm without sorting | C # program for the above approach ; 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 ; Driver code ; Input ; Function Call
code: using System ; using System . Collections . Generic ; public class GFG { static void Rearrange ( int [ ] arr , int K , int N ) { int [ ] ans = new int [ N + 1 ] ; int f = - 1 ; for ( int i = 0 ; i < N ; i ++ ) { ans [ i ] = - 1 ; } for ( int i = 0 ; i < arr . Length ; i ++ ) { if ( arr [ i ] == K ) { K = i ; break ; } } List < int > smaller = new List < int > ( ) ; List < int > greater = new List < int > ( ) ; for ( int i = 0 ; i < N ; i ++ ) { if ( arr [ i ] < arr [ K ] ) smaller . Add ( arr [ i ] ) ; else if ( arr [ i ] > arr [ K ] ) greater . Add ( arr [ i ] ) ; } int low = 0 , high = N - 1 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; if ( mid == K ) { ans [ mid ] = arr [ K ] ; f = 1 ; break ; } else if ( mid < K ) { if ( smaller . Count == 0 ) { break ; } ans [ mid ] = smaller [ smaller . Count - 1 ] ; smaller . RemoveAt ( smaller . Count - 1 ) ; low = mid + 1 ; } else { if ( greater . Count == 0 ) { break ; } ans [ mid ] = greater [ greater . Count - 1 ] ; greater . RemoveAt ( greater . Count - 1 ) ; high = mid - 1 ; } } if ( f == - 1 ) { Console . WriteLine ( - 1 ) ; return ; } for ( int i = 0 ; i < N ; i ++ ) { if ( ans [ i ] == - 1 ) { if ( smaller . Count > 0 ) { ans [ i ] = smaller [ smaller . Count - 1 ] ; smaller . RemoveAt ( smaller . Count - 1 ) ; } else if ( greater . Count > 0 ) { ans [ i ] = greater [ greater . Count - 1 ] ; greater . RemoveAt ( greater . Count - 1 ) ; } } } for ( int i = 0 ; i < N ; i ++ ) Console . Write ( ans [ i ] + " ▁ " ) ; Console . WriteLine ( ) ; } public static void Main ( String [ ] args ) { int [ ] arr = { 10 , 7 , 2 , 5 , 3 , 8 } ; int K = 7 ; int N = arr . Length ; Rearrange ( arr , K , N ) ; } }