用java写一个二分法
时间: 2024-05-08 20:18:20 浏览: 93
好的,下面是用Java写一个二分法的示例代码:
```
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int target = 4;
int result = binarySearch(arr, target);
if (result == -1) {
System.out.println("Element not present");
} else {
System.out.println("Element found at index " + result);
}
}
}
```
该代码会在一个有序的整数数组中查找一个给定的数,如果找到则返回其索引,否则返回 -1。二分法是通过不断缩小查找区间的范围来进行查找,时间复杂度为 O(log n)。
阅读全文