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
def printSmall ( arr , n , k ) : NEW_LINE INDENT for i in range ( k , n ) : NEW_LINE INDENT max_var = arr [ k - 1 ] NEW_LINE pos = k - 1 NEW_LINE for j in range ( k - 2 , - 1 , - 1 ) : NEW_LINE INDENT if ( arr [ j ] > max_var ) : NEW_LINE INDENT max_var = arr [ j ] NEW_LINE pos = j NEW_LINE DEDENT DEDENT if ( max_var > arr [ i ] ) : NEW_LINE INDENT j = pos NEW_LINE while ( j < k - 1 ) : NEW_LINE INDENT arr [ j ] = arr [ j + 1 ] NEW_LINE j += 1 NEW_LINE DEDENT arr [ k - 1 ] = arr [ i ] NEW_LINE DEDENT DEDENT for i in range ( 0 , k ) : NEW_LINE INDENT print ( arr [ i ] , end = " ▁ " ) NEW_LINE DEDENT DEDENT arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] NEW_LINE n = len ( arr ) NEW_LINE k = 5 NEW_LINE printSmall ( arr , n , k ) NEW_LINE