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 top n - element ; If largest is greater than arr [ i ] shift all element one place left ; make arr [ k - 1 ] = arr [ i ] ; print result ; Driver code
function printSmall ( arr , n , k ) { for ( let i = k ; i < n ; ++ i ) { let max_var = arr [ k - 1 ] ; let pos = k - 1 ; for ( let j = k - 2 ; j >= 0 ; j -- ) { if ( arr [ j ] > max_var ) { max_var = arr [ j ] ; pos = j ; } } if ( max_var > arr [ i ] ) { let j = pos ; while ( j < k - 1 ) { arr [ j ] = arr [ j + 1 ] ; j ++ ; } arr [ k - 1 ] = arr [ i ] ; } } for ( let i = 0 ; i < k ; i ++ ) document . write ( arr [ i ] + " " ) ; } let arr = [ 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ] ; let n = 10 ; let k = 5 ; printSmall ( arr , n , k ) ;