Search an element in a sorted array formed by reversing subarrays from a random index | Java program for the above approach ; Function to search an element in a sorted array formed by reversing subarrays from a random index ; Set the boundaries for binary search ; Apply binary search ; Initialize the middle element ; If element found ; Random point is on right side of mid ; From l to mid arr is reverse sorted ; Random point is on the left side of mid ; From mid to h arr is reverse sorted ; Return Not Found ; Drive Code ; Given Input ; Function Call
import java . util . * ; public class GFG { public static int find ( Vector < Integer > arr , int N , int key ) { int l = 0 ; int h = N - 1 ; while ( l <= h ) { int mid = ( l + h ) / 2 ; if ( arr . get ( mid ) == key ) return mid ; if ( arr . get ( l ) >= arr . get ( mid ) ) { if ( arr . get ( l ) >= key && key >= arr . get ( mid ) ) h = mid - 1 ; else l = mid + 1 ; } else { if ( arr . get ( mid ) >= key && key >= arr . get ( h ) ) l = mid + 1 ; else h = mid - 1 ; } } return - 1 ; } public static void main ( String args [ ] ) { Vector < Integer > arr = new Vector < Integer > ( ) ; arr . add ( 10 ) ; arr . add ( 8 ) ; arr . add ( 6 ) ; arr . add ( 5 ) ; arr . add ( 2 ) ; arr . add ( 1 ) ; arr . add ( 13 ) ; arr . add ( 12 ) ; int N = arr . size ( ) ; int key = 8 ; int ans = find ( arr , N , key ) ; System . out . println ( ans ) ; } }