没有bug的二分查找-递归写法

2019 精帖
0 115

题目:在一个有序数组中查找指定的数,如果存在返回其数组下标,否则返回-1

package test;
/**
 * 	二分查找
 * @author 硅谷探秘者(jia)
 */
public class TestMain2 {
	static int a[]= {1,2,3,5,7,8,9,12,45,456,789,1234,45666,45648789};
	static int f=2;
	public static void main(String[] args) {
		int t=find(0,a.length-1);
		System.out.println(t);
	}
	public static int find(int left,int right) {
		int temp = left+((right-left)>>>1);
		if(left<=right) {
			if(a[temp]==f) {
				return temp;
			}else if(a[temp]>f){
				return find(left, temp-1);
			}else {
				return find(temp+1, right);
			}
		}else {
			return -1;
		}
	}
}
留言(0)
加载更多
猜你喜欢