用C语言写一个二分法查找算法
时间: 2023-09-05 22:13:18 浏览: 88
```
#include<stdio.h>
int binary_search(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int result = binary_search(arr, 0, n - 1, target);
if (result == -1) {
printf("Element is not present in array\n");
} else {
printf("Element is present at index %d\n", result);
}
return 0;
}
```
阅读全文