二分查找递归与非递归
时间: 2023-11-05 10:04:26 浏览: 118
二分查找是一种查找算法,可以在有序序列中快速地找到目标元素的位置。它的递归和非递归实现方式如下:
递归实现:
```java
public static int binSearchRecursion(int[] arr, int left, int right, int des) {
if (arr == null || arr.length < 1) {
return -1;
}
if (left <= right) {
int mid = left + (right - left) / 2;
if (des == arr[mid]) {
return mid;
} else if (des < arr[mid]) {
return binSearchRecursion(arr, left, mid - 1, des);
} else {
return binSearchRecursion(arr, mid + 1, right, des);
}
}
return -1;
}
```
非递归实现:
```java
public static int binSearch(int[] arr, int des) {
if (arr == null || arr.length < 1) {
return -1;
}
int left = 0;
int right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (des == arr[mid]) {
return mid;
} else if (des < arr[mid]) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
```
阅读全文