二分查找算法范例

int arr[] = { 1,2,3,4,5,6,7,8,9,10 };//二分查找算法

int k = 7;

int sz = sizeof(arr) / sizeof(arr[0]);

int left = 0;//左下标

int right = sz - 1;//右下标

while(left<=right)//只有此条件满足,才能进入循环

{

int mid = (left + right) / 2;

if (arr[mid] > k)

{

right = mid - 1;

}

else if (arr[mid] < k)

{

left = mid + 1;

}//输出只要没有break,循环继续

else

{

printf("找到了,下标是:%d\n", mid);

break;//只有此项满足了才能跳出循环

}

}

if (left > right)//必须要满足这个条件,才能打印“找不到”

{

printf("找不到\n");

}