-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSearchFromSortedRotatedArray.java
70 lines (58 loc) · 1.23 KB
/
SearchFromSortedRotatedArray.java
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
63
64
65
66
67
68
69
70
/* daily coding problem #58
* assumption: integers in the array are unique
* O(lgn) because we perform 1 binary search all the way
* eliminating half of the array each iteration
*/
public class SearchFromSortedRotatedArray
{
public static void main(String[] args)
{
int arr[] = new int[]{30,32,20,22,25,28,29};
int k = 10;
int index = modifiedBinarySearch(arr, k);
System.out.println(index);
}
public static int modifiedBinarySearch(int[] arr, int k)
{
int left = 0;
int right = arr.length - 1;
int index = -1;
while (left <= right && index == -1)
{
int mid = left + (right - left) / 2;
if(arr[mid] == k)
{
index = mid;
}
// left subarray is sorted
// *** <= bc mid might be left as well at some point
// *** infinite loop if only <
else if(arr[left] <= arr[mid])
{
// if k is within the range of left subarray
if(k >= arr[left] && k < arr[mid])
{
right = mid - 1;
}
else
{
left = mid + 1;
}
}
// right subarray is sorted
else
{
// if k is within the range of right subarray
if(k > arr[mid] && k <= arr[right])
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
return index;
}
}