[C] 纯文本查看 复制代码
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int binary_search(int arr[], int k, int left, int right)
{
while (left <= right)
{
int mid = left + (right - left) / 2;
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
return mid;
}
}
return -1;
}
int main( )
{
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int left = 0;
int right = sizeof(arr) / sizeof(arr[0]) - 1;
int ret = binary_search(arr, 7, left, right);
if (-1 == ret)
{
printf("找不到\n");
}
else
{
printf("找到了,下标是:>%d\n", ret);
}
system("pause");
return 0;
}