classSolution{publicintsearch(int[] nums,int target){int l =0;int r = nums.length -1;while(l < r){int mid =(l + r +1)/2;if(nums[mid]<= target){
l = mid;}else{
r = mid -1;}}if(nums[l]!= target){return-1;}else{return l;}}}
3- ACM 实现
publicclass binarySearch {publicstaticintbinary(int[] nums,int target){int l =0;int r = nums.length-1;while(l<r){int mid =(l+r+1)/2;if(nums[mid]== target){
l = mid;}else{
r = mid-1;}}if(nums[l]== target){return l;}return-1;}publicstaticvoidmain(String[] args){Scanner sc =newScanner(System.in);System.out.println("输入数组长度");int n = sc.nextInt();int[] nums =newint[n];for(int i =0; i < n ; i ++){
nums[i]= sc.nextInt();}System.out.println("输入查找的元素值");int t = sc.nextInt();System.out.println("下标为"+binary(nums,t));}}