#include <stdio.h>
int binarySearch(int arr[], int x, int n) {
int left = 0, right = n - 1, mid;
while (left <= right) {
mid = left + (right - left) / 2;
// 检查x是否在中间
if (arr[mid] == x)
return mid;
// 如果x大于中位数,忽略左半边
if (arr[mid] < x)
left = mid + 1;
// 如果x小于中位数,忽略右半边
else
right = mid - 1;
}
// 如果没有找到,返回-1
return -1;
}
int main() {
int arr[] = {2, 3, 4, 10, 40, 100};
int x = 100;
int n = sizeof(arr) / sizeof(arr[0]);
int result = binarySearch(arr, x, n);
if (result == -1)
printf("元素不存在");
else
printf("元素的索引:%d", result);
return 0;
}