改写成c语言:#include<iostream> using namespace std; void binarySearch(int a[], int left, int right, int aim) { int i = 0; int j = 0; while (left <= right) { int middle = (left + right)/2; //搜索值与中间值相等 if(aim == a[middle]) { i = j = middle; cout << i << " " << j << endl; break; } //搜索值大于中间值 else if(aim > a[middle]) { //x不存在且大于全部数 if(middle == right-1 && aim > a[right]) { cout << right << " " << right + 1; break; } //x等于下一个数 if(aim == a[middle + 1]) i = j = middle + 1; //x在中间数与下一个数之间 else if(aim < a[middle + 1]) { i = middle; j = middle + 1; } else { left = middle + 1; continue; } cout << i << " " << j << endl; break; } //搜索值小于中间值 else { //x不存在且小于全部数 if(middle == 0 && aim < a[0]){ cout << -1 << " " << 0; break; } //x等于上一个数 if(aim == a[middle-1]) i = j = middle - 1; //x在上一个数与中间数之间 else if(aim > a[middle - 1]) { i = middle - 1; j = middle; } else { right = middle; continue; } cout << i << " " << j << endl; break; } } } int main() { int a[1001]; int n, aim; cin >> n; cin >> aim; for(int i=0; i<n; i++) { cin >> a[i]; } binarySearch(a, 0, n-1, aim); return 0; }
时间: 2024-01-13 16:05:54 浏览: 70
使用include <iostream>时一定要加using namespace std
```
#include <stdio.h>
void binarySearch(int a[], int left, int right, int aim) {
int i = 0;
int j = 0;
while (left <= right) {
int middle = (left + right) / 2;
// 搜索值与中间值相等
if (aim == a[middle]) {
i = j = middle;
printf("%d %d\n", i, j);
break;
}
// 搜索值大于中间值
else if (aim > a[middle]) {
// x不存在且大于全部数
if (middle == right - 1 && aim > a[right]) {
printf("%d %d\n", right, right + 1);
break;
}
// x等于下一个数
if (aim == a[middle + 1]) {
i = j = middle + 1;
}
// x在中间数与下一个数之间
else if (aim < a[middle + 1]) {
i = middle;
j = middle + 1;
}
else {
left = middle + 1;
continue;
}
printf("%d %d\n", i, j);
break;
}
// 搜索值小于中间值
else {
// x不存在且小于全部数
if (middle == 0 && aim < a[0]) {
printf("%d %d\n", -1, 0);
break;
}
// x等于上一个数
if (aim == a[middle - 1]) {
i = j = middle - 1;
}
// x在上一个数与中间数之间
else if (aim > a[middle - 1]) {
i = middle - 1;
j = middle;
}
else {
right = middle;
continue;
}
printf("%d %d\n", i, j);
break;
}
}
}
int main() {
int a[1001];
int n, aim;
scanf("%d", &n);
scanf("%d", &aim);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
binarySearch(a, 0, n - 1, aim);
return 0;
}
```
阅读全文