public class BinarySearch {
public static int binarySearch(int[] temp, int target) {
if (temp == null) {
return -1;
}
if (temp.length == 0) {
return 0;
}
int left = 0;
int right = temp.length - 1;
int mid;
while (left <= right) {
mid = left + (right - left) / 2;
if (temp[mid] < target) {
left = mid + 1;
}
else if (temp[mid] > target) {
right = mid - 1;
}
else
return mid;
}
return -1;
}
public static void main(String[] args) {
int[] data = {2, 4, 5, 6, 7, 9};
// binarySearch(data, 5);
System.out.println(binarySearch(data,5));
}
}
Java二分查找
最新推荐文章于 2024-08-18 21:36:31 发布