#include <stdio.h>
#define n 10
int main()
{
int a_size=7;
int left=0;
int right=a_size-1;
int mid;
int a[n]={1,2,3,4,5,6,7};
int target=2;
printf("折半查找算法:\n");
while(left<right)
{
mid=(left+right)/2;
if(a[mid]==target)
{
printf("目标元素对应的下标:%d",mid);
break;//第一次运行的时候在这死循环了
}
else if(a[mid]>target)
{
right=mid-1;
}
else
{
left=mid+1;
}
}
return 0;
}
运行结果: