设a[0:n-1]是一个已排好序的数组。请改写二分搜索算法,使得当搜索元素x不在数组中时,返回小于x的最大元素的位置i和大于x的最小元素位置j。当搜索元素在数组中时,i和j相同,均为x在数组中的位置。并对自己的程序进行复杂性分析。
二分找到大于等于的 L 的位置,最后,如果L的位置的数字等于下x,直接输出一个L位置的数(x).否则,输出L-1位置和L位置的数(数组中与x相邻的两个数字)
#include<bits/stdc++.h>
#define ll long long
#define db double
using namespace std;
const int maxx=100019;
int a[maxx];
int main()
{
int n,x;
scanf("%d%d",&n,&x);// n个数字,查找X
for(int i=0; i<n; i++)
scanf("%d",&a[i]);
int l=0,r=n-1;
while(l<r)
{
int mid=(l+r)/2;
if(a[mid]==x)
{
l=r=mid;
break;
}
a[mid]<x ? l=mid+1 : r=mid ;
}
if(a[l]==x)
printf("%d\n",a[l]);
else
printf("%d %d\n",a[l-1],a[l]);
return 0;
}
/*
7 8
1 3 5 7 9 11 13
*/