kth smallest / largest in a small range unsorted array | Python 3 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
def kthSmallestLargest ( arr , n , k ) : NEW_LINE INDENT max_val = arr [ 0 ] NEW_LINE for i in range ( len ( arr ) ) : NEW_LINE INDENT if ( arr [ i ] > max_val ) : NEW_LINE INDENT max_val = arr [ i ] NEW_LINE DEDENT DEDENT hash = [ 0 for i in range ( max_val + 1 ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT hash [ arr [ i ] ] += 1 NEW_LINE DEDENT count = 0 NEW_LINE for i in range ( max_val + 1 ) : NEW_LINE INDENT while ( hash [ i ] > 0 ) : NEW_LINE INDENT count += 1 NEW_LINE if ( count == k ) : NEW_LINE INDENT return i NEW_LINE DEDENT hash [ i ] -= 1 NEW_LINE DEDENT DEDENT return - 1 NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 11 , 6 , 2 , 9 , 4 , 3 , 16 ] NEW_LINE n = len ( arr ) NEW_LINE k = 3 NEW_LINE print ( " kth ▁ smallest ▁ number ▁ is : " , kthSmallestLargest ( arr , n , k ) ) NEW_LINE DEDENT