human
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.
Driver Code.
Input.
Function Call"
How can the above be solved in Python?
 ... What is a code to rearrange Array to find K using Binary Search algorithm without sorting and the other steps required?
assistant
#Here is code to rearrange Array to find K using Binary Search algorithm without sorting and the other steps required.
 def Rearrange ( arr , K , N ) :
	ans = [ 0 ] * ( N + 1 )
	f = - 1
	for i in range ( N ) :
		ans [ i ] = - 1
	K = arr . index ( K )
	smaller = [ ]
	greater = [ ]
	for i in range ( N ) :
		if ( arr [ i ] < arr [ K ] ) :
			smaller . append ( arr [ i ] )
		elif ( arr [ i ] > arr [ K ] ) :
			greater . append ( arr [ i ] )
	low = 0
	high = N - 1
	while ( low <= high ) :
		mid = ( low + high ) // 2
		if ( mid == K ) :
			ans [ mid ] = arr [ K ]
			f = 1
			break
		elif ( mid < K ) :
			if ( len ( smaller ) == 0 ) :
				break
			ans [ mid ] = smaller [ - 1 ]
			smaller . pop ( )
			low = mid + 1
		else :
			if ( len ( greater ) == 0 ) :
				break
			ans [ mid ] = greater [ - 1 ]
			greater . pop ( )
			high = mid - 1
	if ( f == - 1 ) :
		print ( - 1 )
		return
	for i in range ( N ) :
		if ( ans [ i ] == - 1 ) :
			if ( len ( smaller ) ) :
				ans [ i ] = smaller [ - 1 ]
				smaller . pop ( )
			elif ( len ( greater ) ) :
				ans [ i ] = greater [ - 1 ]
				greater . pop ( )
	for i in range ( N ) :
		print ( ans [ i ] , end = " ▁ " )
	print ( )
if __name__ == " _ _ main _ _ " :
	arr = [ 10 , 7 , 2 , 5 , 3 , 8 ]
	K = 7
	N = len ( arr )
	Rearrange ( arr , K , N )