Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- int search(vector<int>& arr, int target) {
- int n = arr.size();
- //Binary search to find pivot index
- int l = 0, h = n-1;
- //First true for arr[0]-arr[m]>0
- while(l<h){
- int m = l + (h-l)/2;
- if(arr[0]-arr[m]>0){
- h = m;
- }
- else{
- l = m+1;
- }
- }
- int pivot = l;
- //Binary search to search the given target in left sorted array
- l = 0; h = pivot-1;
- //First true for arr[m]>=target
- while(l<h){
- int m = l + (h-l)/2;
- if(arr[m]>=target){
- h = m;
- }
- else{
- l = m+1;
- }
- }
- if(arr[l]==target)return l;
- //Binary search to search the given target in right sorted array
- l = pivot; h = n-1;
- //First true for arr[m]>=target
- while(l<h){
- int m = l + (h-l)/2;
- if(arr[m]>=target){
- h = m;
- }
- else{
- l = m+1;
- }
- }
- if(arr[l]==target)return l;
- return -1; //If element is not present at all
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement