#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int look(int a[], int j, int s)
{
int left = a[0];
int right = a[s - 1];
while (left <= right)
{
int mid = (left + right) / 2;//错误:将本句放在了while外面
if (j > a[mid])//错误:将a[mid]写成了mid
{
left = mid + 1;
}
else if (j < a[mid])
{
right = mid - 1;
}
else
{
return mid;
}
}
return -1;//找不到
}
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 10;
int sz = sizeof(arr) / sizeof(arr[0]);
int rep=look(arr,k,sz);
if (rep != -1)
{
printf("找到了,下标是:%d\n",rep);
}
else
{
printf("没找到");
}
return 0;
}
实现难点:
1、int mid = (left + right) / 2; 将本句放在了while循环外面
2、将a[mid]写成了mid。
运行结果:
k=10,所以结果如下