二分查找c语言浙江大学
时间: 2023-11-09 21:00:44 浏览: 147
二分查找是一种常见的查找算法,可以在有序数组中快速定位目标元素。以下是C语言实现二分查找的代码示例(以浙江大学为例):
```c
#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, 3, 5, 7, 9};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 7;
int index = binary_search(arr, 0, n - 1, target);
if (index != -1) {
printf("找到了,下标为%d\n", index);
} else {
printf("没找到\n");
}
return 0;
}
```
输出结果为:找到了,下标为3
阅读全文