java编写二分查找代码
时间: 2024-01-23 07:12:53 浏览: 88
面是Java编写的二分查找代码:
```java
public class BinarySearch {
//方法1:递归求解
public int recursionSearch(int[] A, int start, int end, int number) {
if (start > end) {
return -1;
}
int mid = (start + end) / 2;
if (A[mid] == number) {
return mid;
} else if (A[mid] > number) {
return recursionSearch(A, start, mid - 1, number);
} else {
return recursionSearch(A, mid + 1, end, number);
}
}
//方法2:迭代求解
public int iterationSearch(int[] A, int number) {
int start = 0;
int end = A.length - 1;
while (start <= end) {
int mid = (start + end) / 2;
if (A[mid] == number) {
return mid;
}
if (A[mid] > number) {
end = mid - 1;
}
if (A[mid] < number) {
start = mid + 1;
}
}
return -1;
}
public static void main(String[] args) {
BinarySearch test = new BinarySearch();
int[] A = {3, 14, 27, 31, 39, 42, 55, 70, 74, 81, 85, 93, 98};
System.out.println("使用递归法求解number = 70的数组下标结果:" + test.recursionSearch(A, 0, A.length - 1, 70));
System.out.println("使用迭代法求解number = 70的数组下标结果:" + test.iterationSearch(A, 70));
}
}
```
阅读全文