Kth smallest or largest element in unsorted Array | Set 4 | Java program for the above approach ; 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
import java . io . * ; class GFG { static int findKthSmallest ( int [ ] arr , int n , int k ) { int max = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( arr [ i ] > max ) max = arr [ i ] ; } int [ ] counter = new int [ max + 1 ] ; int smallest = 0 ; for ( int i = 0 ; i < n ; i ++ ) { counter [ arr [ i ] ] ++ ; } for ( int num = 1 ; num <= max ; num ++ ) { if ( counter [ num ] > 0 ) { smallest += counter [ num ] ; } if ( smallest >= k ) { return num ; } } return - 1 ; } public static void main ( String [ ] args ) { int [ ] arr = { 7 , 1 , 4 , 4 , 20 , 15 , 8 } ; int N = arr . length ; int K = 5 ; System . out . print ( findKthSmallest ( arr , N , K ) ) ; } }