使用函数进行二分查找
程序员文章站
2022-03-13 18:20:53
...
#include <stdio.h>
#include <stdlib.h>
//定义二分查找函数
int searchArray(int arr[], int size, int to_find) {
//确定待查找区间[left, right]
int left = 0;
int right = size - 1;
int mid;
while (left <= right) {
//二分数组
mid = (left + right) / 2;
if (to_find < arr[mid]) {
right = mid - 1;
}
else if (to_find > arr[mid]) {
left = mid + 1;
}
else {
//此处可以返回待查找的数为arr[mid];
return arr[mid];
}
}
//数组不包含待查找数
return -1;
}
int main() {
int a[9] = { 1, 2 ,3, 4, 5, 6, 7, 8, 9 };
printf("%d\n", searchArray(a, 9, 5));
system("pause");
return 0;
}