//二分查找,前提必须是有序
#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;
}
标签:二分,arr,right,int,mid,C语言,flag,查找
From: https://blog.csdn.net/2301_76310379/article/details/136780521