优化这段代码:#include<cstdio> using namespace std; int a[1005]; int main() { int n,x; scanf("%d",&n); for(int i=1;i<=n;i++) { scanf("%d",&a[i]); } scanf("%d",&x); int l=1,r=n,mid; int ans=0; bool flag=false; while(l<r) { mid = (l+r)>>1; if(a[mid]==x) { flag=true; ans++; break; } if(x>a[mid]) { l = mid + 1; } else { r = mid; } ans++; } if(!flag) printf("NO"); else printf("%d",ans); return 0; }
时间: 2024-04-08 19:31:44 浏览: 83
#include <cstdio>
using namespace std;
int a[1005];
int binarySearch(int arr[], int n, int x) {
int l = 1, r = n, mid;
int ans = 0;
bool flag = false;
while (l <= r) {
mid = (l + r) >> 1;
if (arr[mid] == x) {
flag = true;
ans++;
break;
}
if (x > arr[mid]) {
l = mid + 1;
} else {
r = mid - 1;
}
ans++;
}
return flag ? ans : -1;
}
int main() {
int n, x;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
}
scanf("%d", &x);
int result = binarySearch(a, n, x);
if (result == -1) {
printf("NO");
} else {
printf("%d", result);
}
return 0;
}
阅读全文