java写一个二分查找
时间: 2023-07-18 13:34:11 浏览: 38
好的,下面是一个简单的 Java 二分查找示例:
```java
public class BinarySearch {
public static int binarySearch(int[] arr, int x) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == x) {
return mid;
} else if (arr[mid] < x) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1; // 没有找到指定元素,返回 -1
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 12, 14, 16};
int x = 10;
int index = binarySearch(arr, x);
if (index == -1) {
System.out.println("元素 " + x + " 不存在于数组中");
} else {
System.out.println("元素 " + x + " 在数组中的索引为 " + index);
}
}
}
```
该示例使用 `binarySearch` 方法实现二分查找,接收一个整型数组和要查找的元素作为参数,返回该元素在数组中的索引,如果该元素不存在于数组中,返回 -1。
在 `main` 方法中,我们定义了一个整型数组 `arr` 和要查找的元素 `x`,然后调用 `binarySearch` 方法查找该元素在数组中的索引,并输出结果。