欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

用c语言实现折半查找函数

程序员文章站 2023-02-07 10:47:42
#include #include int binsearch(int x, int arr[], int left, in...
#include <stdio.h>
#include <stdlib.h>
int binsearch(int x, int arr[], int left, int right)
{
while (left <= right)
{
int mid = (left+right)/2;
if (arr[mid] == x)
{
return mid;
}
else if (arr[mid] < x)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
return -1;
}
int main()
{
int arr[] = { 2, 6, 20, 66, 177, 199, 600 };
int n;
scanf("%d",&n);
int ret = binsearch(n, arr, 0, sizeof(arr) / sizeof(arr[0] - 1));
if (ret != -1)
{
printf("%d\n", arr[ret]);
}
else
{
printf("not exist\n");
}
system("pause");
return 0;
}