kth smallest / largest in a small range unsorted array | PHP 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
< ? php $ maxs = 1000001 ; function kthSmallestLargest ( & $ arr , $ n , $ k ) { global $ maxs ; $ max_val = max ( $ arr ) ; $ hash = array_fill ( 0 , $ max_val + 1 , NULL ) ; for ( $ i = 0 ; $ i < $ n ; $ i ++ ) $ hash [ $ arr [ $ i ] ] ++ ; $ count = 0 ; for ( $ i = 0 ; $ i <= $ max_val ; $ i ++ ) { while ( $ hash [ $ i ] > 0 ) { $ count ++ ; if ( $ count == $ k ) return $ i ; $ hash [ $ i ] -- ; } } return -1 ; } $ arr = array ( 11 , 6 , 2 , 9 , 4 , 3 , 16 ) ; $ n = sizeof ( $ arr ) / sizeof ( $ arr [ 0 ] ) ; $ k = 3 ; echo " kth ▁ smallest ▁ number ▁ is : ▁ " . kthSmallestLargest ( $ arr , $ n , $ k ) . " STRNEWLINE " ; return 0 ; ? >