JavaAlgorithms/Searches/Perfect BinarySearch

22 lines
445 B
Plaintext
Raw Normal View History

2020-05-19 23:20:48 +08:00
static int binarySearch(int[] arr, int target) {
int low = 0 ;
int high = arr.length - 1 ;
while(low <= high) {
int mid =(low + high) / 2;
if(arr[mid] == target) {
return mid;
}
else if(arr[mid] > target) {
high = mid - 1;
}
else {
low = mid + 1;
}
}
return -1;
}