测试用例:
5 5
2 4 6 6 10
1
3
6
10
11
测试代码:
/*
* 二分查找测试
*/
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 101;
int equalsBinarySearch(const int arr[N], const int &start, const int &end, const int &v)
{
int left = start, right = end - 1;
int middle;
while (left <= right)
{
middle = (left + right) >> 1;
if (arr[middle] == v) return middle;
if (arr[middle] < v) left = middle + 1;
else right = middle - 1;
}
return -1;
}
// 返回第一个大于等于v的下标
int lowerBoundBinarySearch(const int arr[N], const int &start, const int &end, const int &v)
{
// return lower_bound(arr + start, arr + end, v) - arr; // 等同
int left = start, right = end - 1;
int middle;
while (left <= right)
{
middle = (left + right) >> 1;
if (arr[middle] < v) left = middle + 1;
else right = middle - 1;
}
return left;
}
// 第一个大于v的下标
int upperBoundBinarySearch(const int arr[N], const int &start, const int &end, const int &v)
{
// return upper_bound(arr + start, arr + end, v) - arr; // 等同
int left = start, right = end - 1;
int middle;
while (left <= right)
{
middle = (left + right) >> 1;
if (arr[middle] <= v) left = middle + 1;
else right = middle - 1;
}
return left;
}
// 小于等于v的最后一个位置
int upperBoundBinarySearch2(const int arr[N], const int &start, const int &end, const int &v)
{
int left = start, right = end - 1;
int middle;
while (left <= right)
{
middle = (left + right) >> 1;
if (arr[middle] > v) right = middle - 1;
else left = middle + 1;
}
return right;
}
int main()
{
int arr[N];
int n, m, i, x;
scanf("%d %d", &n, &m);
for (i = 0; i < n; i++)
{
scanf("%d", &arr[i]);
}
for (i = 0; i < m; i++)
{
scanf("%d", &x);
printf("%d: %d\n", x, upperBoundBinarySearch(arr, 0, n, x));
}
return 0;
}