二分查找-递归
程序员文章站
2024-03-17 23:05:58
...
public static int myBinarsSearch(int[] a, int key, int start, int end) {
//start一定不能大于end
while (start <= end) {
int middle = (start + end) / 2;
if (key == a[middle]) {
return middle;
} else if (key > a[middle]) {
return myBinarsSearch(a, key, middle + 1, end);
} else if (key < a[middle]) {
return myBinarsSearch(a, key, start, middle - 1);
}
}
return -1;
}
public static void main(String[] args) {
int[] a = { 1, 5, 6, 2, 8, 11, 99 };
int result = Er_digui.myBinarsSearch(a, 99, 0, a.length);
System.out.printf("返回的下标为:%d", result);
}
上一篇: Python基础编程:利用列表实现简单的先进后出、先进先出
下一篇: 实现非递归二分法查询