Search an element in a sorted array formed by reversing subarrays from a random index | C ++ 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 ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; int find ( vector < int > arr , int N , int key ) { int l = 0 ; int h = N - 1 ; while ( l <= h ) { int mid = ( l + h ) / 2 ; if ( arr [ mid ] == key ) return mid ; if ( arr [ l ] >= arr [ mid ] ) { if ( arr [ l ] >= key && key >= arr [ mid ] ) h = mid - 1 ; else l = mid + 1 ; } else { if ( arr [ mid ] >= key && key >= arr [ h ] ) l = mid + 1 ; else h = mid - 1 ; } } return -1 ; } int main ( ) { vector < int > arr = { 10 , 8 , 6 , 5 , 2 , 1 , 13 , 12 } ; int N = arr . size ( ) ; int key = 8 ; int ans = find ( arr , N , key ) ; cout << ans ; }