text: Kth smallest or largest element in unsorted Array | Set 4 | Function to find the Kth smallest element in Unsorted Array ; Initialize the max Element as 0 ; Iterate arr [ ] and find the maximum element in it ; Frequency array to store the frequencies ; Counter variable ; Counting the frequencies ; Iterate through the freq [ ] ; Check if num is present in the array ; Increment the counter with the frequency of num ; Checking if we have reached the Kth smallest element ; Return the Kth smallest element ; Driver Code ; Given array ; Function Call
code: def findKthSmallest ( arr , n , k ) : NEW_LINE INDENT max = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( arr [ i ] > max ) : NEW_LINE INDENT max = arr [ i ] NEW_LINE DEDENT DEDENT counter = [ 0 ] * ( max + 1 ) NEW_LINE smallest = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT counter [ arr [ i ] ] += 1 NEW_LINE DEDENT for num in range ( 1 , max + 1 ) : NEW_LINE INDENT if ( counter [ num ] > 0 ) : NEW_LINE INDENT smallest += counter [ num ] NEW_LINE DEDENT if ( smallest >= k ) : NEW_LINE INDENT return num NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 7 , 1 , 4 , 4 , 20 , 15 , 8 ] NEW_LINE N = len ( arr ) NEW_LINE K = 5 NEW_LINE print ( findKthSmallest ( arr , N , K ) ) NEW_LINE DEDENT