二分查找的递归实现
程序员文章站
2024-03-20 10:20:40
...
import java.util.*;
//二分查找的递归实现
public class T4 {
static int binarysearch(int[] arr, int low, int high, int key){
int mid = (low + high) / 2;
if(low > high)
return -1;
if(key > arr[mid])
return binarysearch(arr, mid + 1, high, key);
else if(key < arr[mid])
return binarysearch(arr, low, mid - 1, key);
else
return mid;
}
public static void main(String[] args) {
int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int index = T4.binarysearch(arr, 0, 9, 9);
System.out.println(index);
}
}
上一篇: 是否同一棵二叉搜索树
下一篇: 部分代码2