human
Can you provide a code to k smallest elements in same order using O ( 1 ) extra space and the other steps required given the following:
k smallest elements in same order using O ( 1 ) extra space | Function to print smallest k numbers in arr [ 0. . n - 1 ].
For each arr [ i ] find whether it is a part of n - smallest with insertion sort concept.
find largest from first k - elements.
if largest is greater than arr [ i ] shift all element one place left.
make arr [ k - 1 ] = arr [ i ].
print result.
Driver program"
How can the above be solved in Python?
assistant
#Here is code to k smallest elements in same order using O ( 1 ) extra space and the other steps required.
 def printSmall ( arr , n , k ) :
	for i in range ( k , n ) :
		max_var = arr [ k - 1 ]
		pos = k - 1
		for j in range ( k - 2 , - 1 , - 1 ) :
			if ( arr [ j ] > max_var ) :
				max_var = arr [ j ]
				pos = j
		if ( max_var > arr [ i ] ) :
			j = pos
			while ( j < k - 1 ) :
				arr [ j ] = arr [ j + 1 ]
				j += 1
			arr [ k - 1 ] = arr [ i ]
	for i in range ( 0 , k ) :
		print ( arr [ i ] , end = " ▁ " )
arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ]
n = len ( arr )
k = 5
printSmall ( arr , n , k )