写一个java的二分法
时间: 2023-05-22 11:04:39 浏览: 118
实现:
```java
public class BinarySearch {
public static int binarySearch(int[] nums, int target) {
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
```
调用:
```java
public class Main {
public static void main(String[] args) {
int[] nums = {1, 5, 8, 12, 15, 18, 20};
int target = 12;
int index = BinarySearch.binarySearch(nums, target);
if (index == -1) {
System.out.println("Target not found");
} else {
System.out.println("Target found at index " + index);
}
}
}
```
以上是二分法的 Java 实现例子,可以参考。