#include <stdio.h>
#include <stdlib.h>
int compare(const void *a, const void *b) {
return (*(int *)a - *(int *)b);
}
int binarySearch(int arr[], int size, int target) {
int left = 0;
int right = size - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
else if (arr[mid] > target) {
right = mid - 1;
}
else {
left = mid + 1;
}
}
return -1;
}
int main() {
int arr[] = {85, 63, 52, 34, 25, 17, 6};
int size = sizeof(arr) / sizeof(arr[0]);
int target = 6;
qsort(arr, size, sizeof(int), compare);
int result = binarySearch(arr, size, target);
if (result != -1) {
printf("元素 %d 存在于数组中,索引为 %d\n", target, result);
} else {
printf("元素 %d 不存在于数组中\n", target);
}
return 0;
}