/
Search in Rotated Sorted Array .cpp
62 lines (58 loc) · 1.17 KB
/
Search in 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
61
62
#include<iostream>
using namespace std;
class Solution {
public:
int search(int A[], int n, int target)
{
//
if(n == 0)
return -1;
if(n == 1)
return target == A[0]?0:-1;
int low = 0;
int high = n-1;
while(low <= high)
{
int mid = low+ (high-low)/2;
if(A[mid] == target)
return mid;
//*********************1st case**********************
if(A[mid] < target)
{
if(A[mid] <A[low]) //mid is in the second half
{
if(target < A[low]) //target is in the second half
low = mid+1;
else
high = mid -1;
}
else // mid is in the first half
low = mid + 1;
}
//***************2nd case**************************
else
{
if(A[mid] >=A[low]) //mid is in the first half
{
if(target >= A[low]) // target is in the first half
high = mid -1;
else
low = mid +1;
}
else // mid is in the second half
high = mid -1 ;
}
}
return -1;
//
}
};
int main(void)
{
Solution s;
int arr[] = {4,5,6,7,8,0,1,2,3,4};
int result = s.search(arr,sizeof(arr)/sizeof(int),7);
cout << result << endl;
getchar();
return 0;
}