k smallest elements in same order using O ( 1 ) extra space | Java for printing smallest k numbers in order ; 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 function
import java . util . * ; import java . lang . * ; public class GfG { public static void printSmall ( int arr [ ] , int n , int k ) { for ( int i = k ; i < n ; ++ i ) { int max_var = arr [ k - 1 ] ; int pos = k - 1 ; for ( int j = k - 2 ; j >= 0 ; j -- ) { if ( arr [ j ] > max_var ) { max_var = arr [ j ] ; pos = j ; } } if ( max_var > arr [ i ] ) { int j = pos ; while ( j < k - 1 ) { arr [ j ] = arr [ j + 1 ] ; j ++ ; } arr [ k - 1 ] = arr [ i ] ; } } for ( int i = 0 ; i < k ; i ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; } public static void main ( String argc [ ] ) { int [ ] arr = { 1 , 5 , 8 , 9 , 6 , 7 , 3 , 4 , 2 , 0 } ; int n = 10 ; int k = 5 ; printSmall ( arr , n , k ) ; } }