使用java 编写一个二分查找
时间: 2024-06-06 08:07:52 浏览: 55
JAVA实现二分查找
public class BinarySearch {
public static int binarySearch(int[] arr, int target) {
int low = 0;
int high = arr.length - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int target = 5;
int index = binarySearch(arr, target);
if (index != -1) {
System.out.println("Target found at index: " + index);
} else {
System.out.println("Target not found in the array");
}
}
}
阅读全文