写一个函数,实现一个有序数组的二分查找。
程序员文章站
2024-03-17 14:34:34
...
#include <stdio.h>
int binary_search(int arr[],int key,int sz)
{
int mid = 0;
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] < key)
left = arr[mid] + 1;
else if (arr[mid] > key)
right = arr[mid] - 1;
else
return mid;
}
return -1;
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int sz = sizeof(arr) / sizeof(arr[0]);
int key = 7;
int ret = binary_search(arr, key, sz);
if (ret == -1)
printf("找不到!\n");
else
printf("找到了!下标为:%d\n", ret);
return 0;
}
上一篇: 牛客网机试题-神奇的口袋
下一篇: 用java实现二分查找