kth smallest / largest in a small range unsorted array | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define maxs  1000001 NEW_LINE int kthSmallestLargest ( int * arr , int n , int k ) { int max_val = * max_element ( arr , arr + n ) ; int hash [ max_val + 1 ] = { 0 } ; 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 ; } int main ( ) { int arr [ ] = { 11 , 6 , 2 , 9 , 4 , 3 , 16 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) , k = 3 ; cout << " kth ▁ smallest ▁ number ▁ is : ▁ " << kthSmallestLargest ( arr , n , k ) << endl ; return 0 ; }