kth smallest / largest in a small range unsorted array | Javascript 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
let maxs = 1000001 ; function kthSmallestLargest ( arr , n , k ) { let max_val = Math . max ( ... arr ) ; let hash = new Array ( max_val + 1 ) ; for ( let i = 0 ; i < hash . length ; i ++ ) { hash [ i ] = 0 ; } for ( let i = 0 ; i < n ; i ++ ) { hash [ arr [ i ] ] ++ ; } let count = 0 ; for ( let i = 0 ; i <= max_val ; i ++ ) { while ( hash [ i ] > 0 ) { count ++ ; if ( count == k ) { return i ; } hash [ i ] -- ; } } return - 1 ; } let arr = [ 11 , 6 , 2 , 9 , 4 , 3 , 16 ] ; let n = arr . length , k = 3 ; document . write ( " " + kthSmallestLargest ( arr , n , k ) ) ;