Skip to content

Instantly share code, notes, and snippets.

@jainal09
Created April 1, 2023 23:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jainal09/d0073e8fbc2ae39cbe4300cb95bae389 to your computer and use it in GitHub Desktop.
Save jainal09/d0073e8fbc2ae39cbe4300cb95bae389 to your computer and use it in GitHub Desktop.
Order Agnostic Binary Search in java
package myPackage.myAlgorithms;
public class MyOrderAgnosticBinarySearch {
public static void main(String[] args) {
int[] nums1 = {-1, 2, 4, 6, 7, 8, 12, 15, 19, 32, 45, 67, 99};
int[] nums2 = {99, 67, 45, 32, 19, 15, 12, 8, 7, 6, 4, 2, -1};
int target = -1;
System.out.println(mySearch(nums1, target));
System.out.println(mySearch(nums2, target));
}
static int mySearch(int[] arr, int target) {
int start = 0;
int end = arr.length - 1;
boolean isAscending = arr[start] < arr[end];
while (start <= end) {
int mid = start + (end - start) / 2;
if (target == arr[mid])
return mid;
if (isAscending) {
if (target < arr[mid]) {
end = mid - 1;
} else {
start = mid + 1;
}
} else {
if (target < arr[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
}
}
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment