用函数写二分查找
程序员文章站
2024-03-17 15:09:22
...
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int binary_search(int arr[],int n,int sz)
{
int left = 0;
int right = sz-1;
int mid = 0;
while(left<=right)
{
mid = (left+right)/2;
if(arr[mid]>n)
{
right = mid-1;
}
else if(arr[mid] < n)
{
left = mid+1;
}
else
return mid;
}
return -1;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
int n = 0;
int ret = 0;
int sz=sizeof(arr)/sizeof(arr[0]);
printf("请输入要查找的:");
scanf("%d",&n);
ret = binary_search(arr,n,sz);
if(ret==-1)
printf("找不到\n");
else
printf("找到了,下标是:%d\n",ret);
return 0;
}
上一篇: js 设置当前时间的后20分钟、后一小时、前一天等等相对时间
下一篇: 打印流输出文件