//二分查找,前提必须是有序
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int sz = sizeof(arr) / sizeof(arr[0]);//求数组长度
int k = 7;//要查找的数
int left = 0;
int right = sz - 1;
int mid = 0;
int flag = 0;//用来标记是否找到
while (left<=right)
{
mid = (left + right) / 2;
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
flag = 1;
printf(" 找到了,下标是%d\n", mid);
break;
}
}
if (flag == 0)
{
printf("未找到\n");
}
return 0;
}
用C语言实现二分查找
最新推荐文章于 2024-11-03 15:43:18 发布