数据结构(二分查找)

public class Search {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] arr=new int[] {1,2,3,4,5,6,7,8,9};
		System.out.println(binerysearch(arr,2));

	}
	public static int binerysearch(int[] arr,int value) {
		int mid=0;
		int low=0;
		int high=arr.length;
		while(true) {
			mid=(low+high)/2;
			if(arr[mid]==value) {
				return mid;
			}else if(low>high){
				return -1;
			}else {
				if(value>arr[mid]) {
					low=mid+1;
				}else {
					high=mid-1;
				}
			}
		}
	}

}

猜你喜欢

转载自blog.csdn.net/silence_hv/article/details/80286848