-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathOrderAgnosticBinarySearch.java
38 lines (37 loc) · 1.16 KB
/
OrderAgnosticBinarySearch.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
public class OrderAgnosticBinarySearch {
public static int orderAgnosticBinarySearch(int[] arr, int target) {
int start = 0;
int end = arr.length - 1;
while (start <= end) {
int mid = start + (end - start) / 2;
if (target == arr[mid]) {
return mid;
}
// Ascending order
if (arr[start] < arr[end]) {
if (target > arr[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
// Descending order
else {
if (target > arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
}
}
return -1;
}
public static void main(String[] args) {
int[] arr1 = {2, 4, 6, 9, 11, 12, 14, 20, 36, 48};
int[] arr2 = {90, 75, 18, 12, 6, 4, 3, 1};
int target1 = 36;
int target2 = 75;
System.out.println(orderAgnosticBinarySearch(arr1, target1));
System.out.println(orderAgnosticBinarySearch(arr2, target2));
}
}