用Java写出二分查到的代码实现
时间: 2024-09-28 09:07:47 浏览: 22
基于java写的在线题库系统源代码.zip
5星 · 资源好评率100%
在Java中,二分查找(Binary Search)通常用于有序数组中查找特定元素。以下是二分查找算法的基本实现:
```java
public class BinarySearch {
public int binarySearch(int[] nums, int target) {
if (nums == null || nums.length == 0) {
return -1; // 数组为空
}
int left = 0;
int right = nums.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2; // 计算中间索引
if (nums[mid] == target) {
return mid; // 找到目标值,返回其索引
} else if (nums[mid] < target) {
left = mid + 1; // 目标大于中间值,更新左边界
} else {
right = mid - 1; // 目标小于中间值,更新右边界
}
}
return -1; // 没找到目标,返回-1
}
// 示例
public static void main(String[] args) {
int[] sortedArray = {1, 3, 5, 7, 9};
int target = 5;
BinarySearch bs = new BinarySearch();
int result = bs.binarySearch(sortedArray, target);
if (result != -1) {
System.out.println("Target " + target + " found at index " + result);
} else {
System.out.println("Target not found in the array");
}
}
}
```
阅读全文