/**
* 全范围二分查找
* 等价于三个子问题
* 左边找(递归)
* 中间比
* 右边找(递归)
* @author lenovo
*
*/
public class 二分查找的递归解法 {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,7,8,9};
int keyIndex = binarySearch(arr, 0, arr.length-1, 10);
System.out.println(keyIndex);
}
public static int binarySearch(int[] arr,int low,int high,int key)
{
if(low > high)
{
return -1;
}
int mid = low + ((high-low)>>1);
int midVal = arr[mid];
if(midVal > key)
{
return binarySearch(arr, low, mid-1, key);
}else if(midVal < key)
{
return binarySearch(arr, mid+1, high, key);
}
return mid;
}
}
wyh奔跑 发布了31 篇原创文章 · 获赞 3 · 访问量 4407 私信 关注