-
Notifications
You must be signed in to change notification settings - Fork 688
/
RotatedBinarySearch.java
58 lines (44 loc) · 1.79 KB
/
RotatedBinarySearch.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
package search;
public class RotatedBinarySearch {
/*
* Binary Search using recursion
* Time complexity - Olog(n)
* Memory Complexity - O(logn) - as it will consume memory on the stack
* */
public static int rotatedBinarySearch(int[] arr, int n, int low, int high) {
if(low > high) return -1;
int middle = low + ((high-low)/2);
if(arr[middle] == n) return middle;
/*
* Step 1: check if the n value is less than the middle value
* Step 2: Check if the first value is less than the middle value
* Step 3: Check if the first value is less than the n value
* */
if(n < arr[middle] && arr[low] < arr[middle] && n>= arr[low]) {
return rotatedBinarySearch(arr, n, low, middle-1);
/*
* Step 1: check if the n value is greater than the middle value
* Step 2: Check if the middle value is less than the highest value
* Step 3: Check if the highest value is <= the n value
* */
} else if(n > arr[middle] && arr[middle] < arr[high] && n <= arr[high]) {
return rotatedBinarySearch(arr, n, middle+1, high);
/*
* Step 1: check if the first value is greater than the middle value
* */
} else if(arr[low] > arr[middle]) {
return rotatedBinarySearch(arr, n, low, middle-1);
/*
* Step 1: check if the last value is less than the middle value
* */
} else if(arr[high] < arr[middle]) {
return rotatedBinarySearch(arr, n, middle+1, high);
}
return -1;
}
public static void main(String[] args) {
int[] arr = {5, 6, 7, 8, 9, 10, 1, 2, 3};
int n = 3;
System.out.println(rotatedBinarySearch(arr, n, 0, arr.length-1));
}
}