输出在数组中第一个大于等于查找值的位置,如果数组中不存在这样的数,则输出数组长度加一。
import java.util.Scanner;
/*
* Project_name:二分查找
5 3
1 2 3 3 5
*/
public class Main{
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int v=sc.nextInt();
int[] ch=new int[n];
for(int i=0;i<n;i++) {
ch[i]=sc.nextInt();
}
// System.out.println(v);
System.out.println(BinarySearch(v,ch)+1);
}
private static int BinarySearch(int v,int[] ch) {
// TODO Auto-generated method stub
int low=0;
int high=ch.length-1;
while(low<=high) {
int mid=(low+high)/2;
if(v<=ch[mid])
high= mid-1;
else if(v>ch[mid])
low=mid+1;
}
// System.out.println(low);
if(low<ch.length&&ch[low]>=v) {
return low;
}else {
return ch.length;
}
}
}