用Java代码实现二分查找算法对一个有序数列进行查找
时间: 2023-05-28 12:05:10 浏览: 90
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) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] > target) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 3, 5, 7, 9};
int target = 5;
int index = binarySearch(arr, target);
if (index == -1) {
System.out.println("Target not found");
} else {
System.out.println("Target found at index " + index);
}
}
}
阅读全文