public class BinarySearch {
public static void main(String[] args) {
int[] array = {1, 8, 10, 89, 1000, 1234};
int index = binarySearch(array, 0, array.length - 1, 8);
if (index != -1) {
System.out.println("index = " + index);
} else {
System.out.println("没有找到~");
}
}
public static int binarySearch(int[] array, int left, int right, int value) {
if (left > right) {
return -1;
}
int mid = (left + right) / 2;
int midValue = array[mid];
if (value > midValue) {
return binarySearch(array, mid + 1, right, value);
} else if (value < midValue) {
return binarySearch(array, left, mid - 1, value);
} else {
return mid;
}
}
}
二分查找递归实现
最新推荐文章于 2024-09-14 10:04:15 发布