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 Code
< ? php function printSmall ( $ arr , $ n , $ k ) { for ( $ i = $ k ; $ i < $ n ; ++ $ i ) { $ max_var = $ arr [ $ k - 1 ] ; $ pos = $ k - 1 ; for ( $ j = $ k - 2 ; $ j >= 0 ; $ j -- ) { 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 ++ ; } $ arr [ $ k - 1 ] = $ arr [ $ i ] ; } } for ( $ i = 0 ; $ i < $ k ; $ i ++ ) echo $ arr [ $ i ] , " ▁ " ; } $ arr = array ( 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 ) ; $ n = count ( $ arr ) ; $ k = 5 ; printSmall ( $ arr , $ n , $ k ) ; ? >