Kth Smallest Element in a sorted array formed by reversing subarrays from a random index | Java program for the above approach ; Function to find the Kth element in a sorted and rotated array at random point ; Set the boundaries for binary search ; Apply binary search to find R ; Initialize the middle element ; Check in the right side of mid ; Else check in the left side ; Random point either l or h ; Return the kth smallest element ; Driver Code ; Given Input ; Function Call
class GFG { public static int findkthElement ( int arr [ ] , int n , int K ) { int l = 0 ; int h = n - 1 , r ; while ( l + 1 < h ) { int mid = ( l + h ) / 2 ; if ( arr [ l ] >= arr [ mid ] ) l = mid ; else h = mid ; } if ( arr [ l ] < arr [ h ] ) r = l ; else r = h ; if ( K <= r + 1 ) return arr [ r + 1 - K ] ; else return arr [ n - ( K - ( r + 1 ) ) ] ; } public static void main ( String args [ ] ) { int [ ] arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int n = arr . length ; int K = 3 ; System . out . println ( findkthElement ( arr , n , K ) ) ; } }