现有数组a[8]={1,3,8,9,6,2,4,7},请使用编写折半算法查找6的位置。
时间: 2024-04-07 21:24:46 浏览: 31
以下是使用折半算法查找数组中元素位置的示例代码:
```c
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
}
if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 3, 8, 9, 6, 2, 4, 7};
int target = 6;
int size = sizeof(arr) / sizeof(arr[0]);
int position = binarySearch(arr, 0, size - 1, target);
if (position != -1) {
printf("The position of %d is %d\n", target, position);
} else {
printf("%d is not found in the array\n", target);
}
return 0;
}
```