9. Binary search
Title description
Please implement binary search for ascending arrays with repeated numbers.
The output is the first position in the array that is greater than or equal to the search value. If there is no such number in the array (meaning there is no number greater than or equal to the search value), the length of the output array is increased by one.
enter
5,4,[1,2,4,4,5]
return value
3
Description
输出位置是从1开始算的
analysis
1. The main algorithm idea is the binary search idea, that is, the binary search idea.
2. The main difficulty of this question is to understand the meaning of the question, n is the length of the array, v is the search target, and a is the target array
3. First of all, we must make it clear that binary search is only applicable to ordered arrays, and secondly, we are performing operations on the topic itself
4. Determine an intermediate position, then compare with the target value v, repeat this operation
Code
public int upper_bound_ (int n, int v, int[] a) {
int i=0;
int j=n-1;
int mid = (i+j)/2;
while(i<=j) {
if(a[mid]<v) {
i=mid+1;
mid = (i+j)/2;
}
else if(mid>0&&a[mid-1]>=v) {
j=mid-1;
mid=(i+j)/2;
}else{
return mid+1;
}
}
return n+1;
}
}