-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotated binary search
More file actions
60 lines (59 loc) · 1.77 KB
/
rotated binary search
File metadata and controls
60 lines (59 loc) · 1.77 KB
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
public class RotatedSortedArray {
static int search(int[] a, int target){
int st = 0, end = a.length-1;
while(st <= end){
int mid = st + (end-st)/2;
if(a[mid] == target){
return mid;
}
else if (a[mid] < a[end]){ // mid to end is sorted
if(target > a[mid] && target <= a[end]){
st = mid+1;
} else {
end = mid-1;
}
} else { // st to mid is sorted
if(target >= a[st] && target < a[mid]){
end = mid-1;
} else {
st = mid+1;
}
}
}
return -1;
}
// duplicate elements
static int search_(int[] a, int target){
int st = 0, end = a.length-1;
while(st <= end){
int mid = st + (end-st)/2;
if(a[mid] == target){
return mid;
}
else if(a[st] == a[mid] && a[end] == mid){
st++;
end--;
}
else if (a[mid] <= a[end]){ // mid to end is sorted
if(target > a[mid] && target <= a[end]){
st = mid+1;
} else {
end = mid-1;
}
} else { // st to mid is sorted
if(target >= a[st] && target < a[mid]){
end = mid-1;
} else {
st = mid+1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] a = {1, 1, 1, 2, 2, 3, 1};
int target = 10;
// System.out.println(search(a, target));
System.out.println(search_(a, target));
}
}