human
Give me a code to sort an array with swapping only with a special element is allowed and the other steps required given the following:
Sort an array with swapping only with a special element is allowed | n is total number of elements . index is index of 999 or space . k is number of elements yet to be sorted ..
Print the sorted array when loop reaches the base case.
Else if k > 0 and space is at 0 th index swap each number with space and store index at second last index.
If space is neither start of array nor last element of array and element before it greater than / the element next to space.
First swap space and element next to space in case of { 3 , 999 , 2 } make it { 3 , 2 , 999 }.
Than swap space and greater element convert { 3 , 2 , 999 } to { 999 , 2 , 3 }.
Wrapper over sortRec ..
Find index of space ( or 999 ).
Invalid input.
Driver Code"
How can the above be solved in Python?
assistant
#Here is code to sort an array with swapping only with a special element is allowed and the other steps required.
 def sortRec ( arr , index , k , n ) :
	if ( k == 0 ) :
		for i in range ( 1 , n ) :
			print ( arr [ i ] , end = " ▁ " )
		print ( 999 , end = " " )
	elif ( k > 0 and index == 0 ) :
		index = n - 2
		for i in range ( 1 , index + 1 ) :
			arr [ i - 1 ] = arr [ i ]
		arr [ index ] = 999
	if ( index - 1 >= 0 and index + 1 < n and arr [ index - 1 ] > arr [ index + 1 ] ) :
		arr [ index ] , arr [ index + 1 ] = arr [ index + 1 ] , arr [ index ]
		arr [ index - 1 ] , arr [ index + 1 ] = arr [ index + 1 ] , arr [ index - 1 ]
	else :
		if ( index - 1 < 0 ) :
			return
		arr [ index ] , arr [ index - 1 ] = arr [ index - 1 ] , arr [ index ]
	sortRec ( arr , index - 1 , k - 1 , n )
def sort ( arr , n ) :
	index = - 1
	for i in range ( n ) :
		if ( arr [ i ] == 999 ) :
			index = i
			break
	if ( index == - 1 ) :
		return
	sortRec ( arr , index , n , n )
arr = [ 3 , 2 , 999 , 1 ]
n = len ( arr )
sort ( arr , n )