C语言习题16
程序员文章站
2022-07-15 16:27:46
...
写一个函数,实现一个整形有序数组的二分查找
//数组传参,传过去的不是整个数组,而是第一个元素的地址
#include <stdio.h>
int binSearch(int arr[], int size, int x)
{
int left = 0;
int right = size - 1;
int mid = 0;
while (left <= right)
{
mid = left + ((right - left) / 2);
if (x < arr[mid])
{
right = mid - 1;
}
else if (x > arr[mid])
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9};
int size = sizeof(arr) / sizeof(arr[0]);
int x = 6;
int index = binSearch(arr, size, x);
if (index < 0)
{
printf("not fonud!\n");
return 1;
}
printf("found it:%d\n",index);
return 0;
}
上一篇: PHP 表单验证 - 必填字段