-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSearchInRotatedSortedArray.java
More file actions
48 lines (38 loc) · 1005 Bytes
/
Copy pathSearchInRotatedSortedArray.java
File metadata and controls
48 lines (38 loc) · 1005 Bytes
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
// solved. both small and large cases.
/*
* Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
You are given a target value to search. If found in the array return its index, otherwise return -1.
You may assume no duplicate exists in the array.
*/
public class SearchInRotatedSortedArray {
public static void main(String[] args){
int[] A = new int[]{1};
System.out.print( search(A,0) );
}
public static int search(int[] A, int target) {
int s = 0;
int e = A.length - 1;
while(s <= e){
int m = (s + e) / 2;
if(A[m] == target) return m;
if( A[m] >= A[s] ){
if(target >= A[s] && target < A[m]){
e = m - 1;
}
else{
s = m + 1;
}
}
else if(A[m] < A[s] ){
if(target > A[m] && target <= A[e]){
s = m + 1;
}
else{
e = m - 1;
}
}
}
return -1;
}
}