欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

二分查找的递归写法

程序员文章站 2022-04-07 17:51:40
...
package 蓝桥杯1;

public class ERFGDG {
	//int mid;
	public static void main(String[] args) {
		int ar[]= {1,5,6,8,10,22,33,66,89,90};
		System.out.print(a(ar,0,0,ar.length-1));
		
	}
static int a(int arr[],int key,int start,int end) {
	int mid;
	if(start>end) return -1;
	 
	else {  mid=(start+end)>>>1;
	if(key>arr[mid]) 
		return a(arr,key,mid+1,end);
	else if(key==arr[mid])
		return mid;
	else if(key<arr[mid]) 
		return a(arr,key,start,mid-1);}
	return -1;
	
}
}package 蓝桥杯1;

public class ERFGDG {
	//int mid;
	public static void main(String[] args) {
		int ar[]= {1,5,6,8,10,22,33,66,89,90};
		System.out.print(a(ar,8,0,ar.length-1));
		
	}
static int a(int arr[],int key,int start,int end) {
	
	if(start>end) return -1;
	 
	 int mid=(start+end)>>>1;
	if(key>arr[mid]) 
		return a(arr,key,mid+1,end);
	else if(key==arr[mid])
		return mid;
	else  
		return a(arr,key,start,mid-1);

	
}
}

这样,就考虑了所以情况,不用在最后写return -1
mid可定义在成员变量中,因为每次都是先计算值给他,再判断

相关标签: java java