#include<stdio.h>
int dinarysearch(int arr[],int left,int right,int value)
{
int middle=(left+right)/2;
if(left>right)
return -1;
if(value>arr[middle])
return dinarysearch(arr,middle+1,right,value);
if(value<arr[middle])
return dinarysearch(arr,left,middle-1,value);
if(value==arr[middle])
return middle;
}
int main()
{
int arr[]={1,2,3,4,5,6,7};
int value=2;
int i=dinarysearch(arr,0,6,value);
printf("%d\n",i);
getch();
return 0;
int dinarysearch(int arr[],int left,int right,int value)
{
int middle=(left+right)/2;
if(left>right)
return -1;
if(value>arr[middle])
return dinarysearch(arr,middle+1,right,value);
if(value<arr[middle])
return dinarysearch(arr,left,middle-1,value);
if(value==arr[middle])
return middle;
}
int main()
{
int arr[]={1,2,3,4,5,6,7};
int value=2;
int i=dinarysearch(arr,0,6,value);
printf("%d\n",i);
getch();
return 0;
}
改进,修改middle的取值,插值查找:
int x=(value-arr[left])/(arr[right]-arr[left]);
int middle=left+x*(right-value);