给我一个二分查找法的C语言代码
时间: 2023-06-02 10:06:05 浏览: 100
C语言二分查找法
当然,以下是一个简单的二分查找法的 C 代码:
```
#include <stdio.h>
int binarySearch(int arr[], int low, int high, int target) {
while (low <= high) {
int mid = low + (high - low) / 2;
if (arr[mid] == target)
return mid;
else if (arr[mid] < target)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}
int main() {
int arr[] = {2, 4, 6, 8, 10, 12, 14, 16, 18, 20};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 6;
int result = binarySearch(arr, 0, n - 1, target);
if (result == -1)
printf("Element not found in array");
else
printf("Element found at index %d", result);
return 0;
}
```
阅读全文