-
Notifications
You must be signed in to change notification settings - Fork 0
/
Search in Rotated Sorted Array.cpp
54 lines (52 loc) · 1.19 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
// Search in Rotated Sorted Array
int search(int A[], int n, int target) {
if(n == 0){
return -1;
}
int left = 0;
int right = n;
int mid;
int first = A[0];
if(target == first){
return 0;
}
else if(target < first){
while(right > left){
mid = (left+right)/2;
if(A[mid] == target){
return mid;
}
if(A[mid] < first){
if(target < A[mid]){
right = mid;
}
else{
left = mid+1;
}
}
else{ //first < A[mid]
left = mid+1;
}
}
}
else{ // first < target
while(right > left){
mid = (left+right)/2;
if(A[mid] == target){
return mid;
}
if(A[mid] < first){
right = mid;
}
else{ // A[mid] > first
if(A[mid] < target){
left = mid+1;
}
else{ //target > A[mid]
right = mid;
}
}
}
}
return -1;
}