-
Notifications
You must be signed in to change notification settings - Fork 62
/
search_rotated_sorted_array.cpp
60 lines (42 loc) · 1.18 KB
/
search_rotated_sorted_array.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
// C++ Program to search an element
// in a sorted and pivoted array
#include<bits/stdc++.h>
using namespace std;
// Standard Binary Search function
int search(vector<int>& nums, int target) {
int l = 0, h = nums.size()-1, mid;
while(l<=h){
mid = l+(h-l)/2;
if(nums[mid] == target)
return mid;
if(nums[l] <= nums[mid]){
if(target >= nums[l] && target <= nums[mid])
h = mid -1;
else
l = mid + 1;
}
else{
if (target >= nums[mid] && target <= nums[h])
l = mid + 1;
else
h = mid - 1;
}
}
return -1;
}
// Driver program to check above functions
int main()
{
int n; //Size of the array
cin>>n;
vector<int> nums;
for(int i=0;i<n;i++){
int a;
cin>>a;
nums.push_back(a);
}
int k; //Element to be searched
cin>>k;
cout<<search(nums,k)<<endl;
return 0;
}