Created
April 1, 2023 23:51
-
-
Save jainal09/d0073e8fbc2ae39cbe4300cb95bae389 to your computer and use it in GitHub Desktop.
Order Agnostic Binary Search in java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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