一、代码
#include<stdio.h>
int FindData(int arr[], int num, int who)
{
int left = 0; int right = num - 1;
while (right >= left)
{
int mid = (right + left) / 2;
if (who< arr[mid]) {
right = mid-1;
}
else if (who > arr[mid]) {
left = mid+1;
}
else {
return mid;
}
}
return -1;//找不到返回-1;
}
int main()
{
int who = 6;
int arr[] = { 1,2,3,4,6,7,8,11,44,55,66 ,};
int num = sizeof(arr)/sizeof(arr[0]);
int index = FindData(arr, num, who);
printf("index:%d\n", index);
return 0;
}
二、注意
right和left的更新
mid每次获取需要去掉本身mid的下标