Skip to content

Commit 6de0711

Browse files
Order Agnostic Binary Searcg
1 parent 0781a06 commit 6de0711

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

OrdABS.java

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
public class OrderAgnosticBS {
2+
public static void main(String[] args) {
3+
// int[] arr = {-18, -12, -4, 0, 2, 3, 4, 15, 16, 18, 22, 45, 89};
4+
int[] arr = {99, 80, 75, 22, 11, 10, 5, 2, -3};
5+
int target = 22;
6+
int ans = orderAgnosticBS(arr, target);
7+
System.out.println(ans);
8+
}
9+
10+
static int orderAgnosticBS(int[] arr, int target) {
11+
int start = 0;
12+
int end = arr.length - 1;
13+
14+
// find whether the array is sorted in ascending or descending
15+
boolean isAsc = arr[start] < arr[end];
16+
17+
while(start <= end) {
18+
// find the middle element
19+
// int mid = (start + end) / 2; // might be possible that (start + end) exceeds the range of int in java
20+
int mid = start + (end - start) / 2;
21+
22+
if (arr[mid] == target) {
23+
return mid;
24+
}
25+
26+
if (isAsc) {
27+
if (target < arr[mid]) {
28+
end = mid - 1;
29+
} else {
30+
start = mid + 1;
31+
}
32+
} else {
33+
if (target > arr[mid]) {
34+
end = mid - 1;
35+
} else {
36+
start = mid + 1;
37+
}
38+
}
39+
}
40+
return -1;
41+
}
42+
}

0 commit comments

Comments
 (0)