二分查找法

#include<stdio.h>
#include<string.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);
int you = sz - 1;
int zuo = 0;
int i = 0;
printf("请输入需要查找的数字(1~10):");
scanf_s("%d", &i);
for (;zuo <= you;)
{
int zhong = (zuo + you) / 2;
if (arr[zhong] > i)
{
you = zhong - 1;
}
else if (arr[zhong] < i)
{
zuo = zhong + 1;
}
else
{
printf("找到了,下标是%d", zhong);
break;
}
}
if (zuo > you)
{
printf("很抱歉,找不到");
}
return 0;
}
发表评论

相关文章