kth smallest / largest in a small range unsorted array | Java program of kth smallest / largest in a small range unsorted array ; Storing counts of elements ; Traverse hash array build above until we reach k - th smallest element . ; Driver code
import java . util . Arrays ; class GFG { static int maxs = 1000001 ; static int kthSmallestLargest ( int [ ] arr , int n , int k ) { int max_val = Arrays . stream ( arr ) . max ( ) . getAsInt ( ) ; int hash [ ] = new int [ max_val + 1 ] ; for ( int i = 0 ; i < n ; i ++ ) { hash [ arr [ i ] ] ++ ; } int count = 0 ; for ( int i = 0 ; i <= max_val ; i ++ ) { while ( hash [ i ] > 0 ) { count ++ ; if ( count == k ) { return i ; } hash [ i ] -- ; } } return - 1 ; } public static void main ( String [ ] args ) { int arr [ ] = { 11 , 6 , 2 , 9 , 4 , 3 , 16 } ; int n = arr . length , k = 3 ; System . out . println ( " kth ▁ smallest ▁ number ▁ is : ▁ " + kthSmallestLargest ( arr , n , k ) ) ; } }