二分查找

二分查找(递归)

package _2查找与排序2;

public class 二分查找 {
public static void main(String[] args) {
	int arr[]= {2,35,3,4,5,10,7,7,8,10};
	int key=6;//下标
	int number= binarysearch(arr,0,arr.length,key);
	System.out.println(number);
}
private static int binarysearch(int[] arr, int a, int b, int key) {
	// TODO Auto-generated method stub
	while(a<=b) {
	if(a>b) {
		return -1;
	}
	int zhongtager=a+((b-a>>1)); //定中下标
	int zhong=arr[zhongtager];//定中值
	if(zhong<key) {
		a=a+1;
	}else if(zhong>key) {
		b=b-1;
	}
	else return zhong;
		
	}
	return -(a+1);//key not found
}
}

你可能感兴趣的:(算法,二分法)