用二分法在有序表{3,4,10,13,33,42,46,63,76,78,95,96,120}中查找一个给定的数。c语言
时间: 2024-01-11 10:02:42 浏览: 41
以下是使用二分法在有序表中查找给定数的C语言代码示例:
```c
#include <stdio.h>
int binarySearch(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
}
if (arr[mid] < key) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {3, 4, 10, 13, 33, 42, 46, 63, 76, 78, 95, 96, 120};
int n = sizeof(arr) / sizeof(arr[0]);
int key;
printf("请输入要查找的数:");
scanf("%d", &key);
int result = binarySearch(arr, 0, n - 1, key);
if (result == -1) {
printf("not found");
} else {
printf("weizhi:%d", result);
}
return 0;
}
```
阅读全文