用c语言写一个代码,要求是:用折半查找法在(05 13 19 21 37 56 64 75 80 88 92)表中査找元素21。
时间: 2023-06-04 20:07:07 浏览: 125
用C语言进行。折半查找
好的,以下是代码:
```c
#include <stdio.h>
int binary_search(int arr[], int len, int target)
{
int low = 0;
int high = len - 1;
while (low <= high)
{
int mid = (low + high) / 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[] = {05, 13, 19, 21, 37, 56, 64, 75, 80, 88, 92};
int len = sizeof(arr) / sizeof(arr[0]);
int target = 21;
int index = binary_search(arr, len, target);
if (index >= 0)
{
printf("%d is found at index %d.\n", target, index);
}
else
{
printf("%d is not found.\n", target);
}
return 0;
}
```
运行结果为:
```
21 is found at index 3.
```
阅读全文