【C】折半查找法
程序员文章站
2024-03-20 18:20:22
...
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include<stdlib.h>
void main()
{
int arr[] = { 1,3,5,7,9,11,13,15,17,19 };
int key=0,mid=0, left = 0, right = sizeof(arr) / 4 - 1;
printf("请输入哟个要查找的数字:");
scanf("%d", &key);
for (left = 0; left <=right; )
{
mid = (left + right) / 2;
if (key>arr[mid])
{
left = mid+1;
}
else if (key < arr[mid])
{
right = mid-1;
}
else
{
break;
}
}
if(left<=right)
printf("找到了\n");
else
{
printf("没找到\n");
}
system("pause");
}