在有序数列中查找某个数,就可以使用二分查找(折半查找)
#include<stdio.h>
int bin_search(int arr[], int left, int right, int key)
{
while (left <= right)
{
int mid = left + (right - left)/2;
if(arr[mid]==key)
{
return mid;
}
else
{
if (arr[mid] < key)
{
left = mid + 1;
}
else
{
right = mid - 1;
}
}
}
return -1;
}
int main()
{
int key=7;
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 result = bin_search(arr, left, right, key);
if (result==-1)
{
printf("没有找到\n");
}
else
{
printf("%d\n", result);
}
return 0;
}
运行结果