-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
56 lines (46 loc) · 1.29 KB
/
solution.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
class Solution
{
public:
int findPos(int a[], int left, int right)
{
if (left > right)
return -1;
int mid = left + (right - left) / 2;
if (a[left] <= a[mid])
{
int pos = findPos(a, mid + 1, right);
if (pos == -1)
return left;
else
return a[left] < a[pos] ? left : pos;
}
else
{
int pos = findPos(a, left, mid - 1);
if (pos == -1)
return mid;
else
return a[pos] < a[mid] ? pos : mid;
}
}
int bsearch(int a[], int left, int right, int key)
{
if (left > right)
return -1;
int mid = left + (right - left) / 2;
if (a[mid] == key)
return mid;
else if (a[mid] < key)
return bsearch(a, mid + 1, right, key);
else
return bsearch(a, left, mid - 1, key);
}
int search(int A[], int n, int target)
{
int pos = findPos(A, 0, n - 1);
int index = bsearch(A, 0, pos - 1, target);
if (index != -1)
return index;
return bsearch(A, pos, n - 1, target);
}
};