二分查找法(自定义函数)

时间:2022-11-30 11:18:57
#pragma warning(disable:4996)
#include<stdio.h>
int erfenchazhao(int arr[],int n,int quan) //自定义的一个函数
{
int you = quan-1;
int zuo = 0;
while (zuo <= you)
{
int zhong = (zuo + you) / 2;
if (arr[zhong] > n)
{
you = zhong - 1;
}
else if (arr[zhong] < n)
{
zuo = zhong + 1;
}
else
{
return zhong;
}
}
return -1;
}
int main()
{
int n = 0; //想查找的数
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int quan = sizeof(arr) / sizeof(arr[0]);//先在外面求好再把这个传过去
printf("请输入你想查找的数字n(1~10):");
scanf("%d", &n);
int i = erfenchazhao(arr, n, quan); //传不了一个数组过去
if (i == -1)
{
printf("找不到");
}
else
{
printf("找到了,下标是%d", i);
}
return 0;
}