用递归的方法实现二分法查找(二分法查找的前提是数据有序)
#include <stdio.h>
#include <stdlib.h>
// 二分查找-数据有序
int _binary_find(int arr[],int left,int right,int key)
{
if(left >= right) return -1;
int p = (left+right)/2;
if(arr[p] == key) return p;
if(arr[p] > key)
return _binary_find(arr,left,p,key);
else
return _binary_find(arr,p+1,right,key);
}
int binary_find(int arr[],size_t len,int key)
{
return _binary_find(arr,0,len,key);
}
int main()
{
int arr[10] = {};
for(int i=0; i<10; i++)
{
arr[i] = i+10;
printf("%d ",arr[i]);
}
printf("
");
printf("%d
",binary_find(arr,10,18));
}
下面是我用循环的方法实现的代码
#include <stdio.h>
#include <stdlib.h>
// 使用循环实现二分查找
int binary_find(int arr[],size_t len,int key)
{
int left = 0 , right = len;
while(left < right)
{
int p = (left + right) / 2;
if(arr[p] == key) return p;
if(arr[p] > key)
right = p;
else
left = p+1;
}
return -1;
}
int main()
{
int arr[10] = {};
for(int i=0; i<10; i++)
{
arr[i] = i+10;
printf("%d ",arr[i]);
}
printf("
");
printf("%d
",binary_find(arr,10,17));
}