【JAVA】BinarySearch

public class BinarySearch {
	static public int binarySearch(int[] arr, int num) {
		int l = 0, u = arr.length - 1;
		while (l <= u) {
			int curr = (l + u) / 2;
			if (arr[curr] == num) {
				System.out.println("the index is :" + curr);
				return curr;
			}
			if (arr[curr] > num) {
				u = curr - 1;
			}
			if (arr[curr] < num) {
				l = curr + 1;
			}
		}
		System.out.println("sorry,can't find the num:"+num);
		return -1;
	}
	static public void main(String args[]){
		int[] arr = {2,3,4,5,11,22,33,44,88,99,101};
		try{
			if(binarySearch(arr, 44)!=7)throw new Exception();
			if(binarySearch(arr, 2)!=0)throw new Exception();
			if(binarySearch(arr, 101)!=10)throw new Exception();
			if(binarySearch(arr, 332)!=-1)throw new Exception();
		}catch(Exception ex){
			ex.printStackTrace();
		}
	}
}

【JAVA】BinarySearch,布布扣,bubuko.com

【JAVA】BinarySearch

上一篇:进程与线程的区别


下一篇:Java 内部类