用JAVA语言写一段二分查找的代码
时间: 2023-03-12 14:03:27 浏览: 79
C和Java的二分查找代码实现
// 二分查找的代码:
public class BinarySearch {
public static int binarySearch(int[] array, int target) {
int left = 0;
int right = array.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (array[mid] == target) {
return mid;
} else if (array[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
阅读全文