折半查找:
#include<stdio.h>
int Binary_Search(int a[],int n,int key)
{
int low, high ,mid;
low=0;
high =n-1;
while(low<=high)
{
mid=(low+high)/2;
if(key>a[mid])
low=mid+1;
else if(key<a[mid])
high=mid-1;
else
return mid;
}
return 0;
}
int main()
{
int a[11]= {0,1,16,24,35,47,59,62,73,88,99};
int addr,aim;
printf("请输入要查找的数;");
scanf("%d",&aim);
addr= Binary_Search(a,11,aim);
printf("%d",addr);
return 0;
}
改进:
折半查找中,mid=(low+high)/2;
改为mid=low+1/2(high-low) = low+(high-low)*(key-a[low])/(a[high]-a[low]).
python实现
f = [1, 2, 5, 6, 7, 8, 94, 5, 42, 42, 24, 5, 45, 4, 5, 45, 78, 7, 98]
f=sorted(f) #有序的序列才能实现折半查找
key =int( input("请输入要查找的数"))
def Find(key, a):
lo=0
hi=len(a)-1
while lo<=hi:
mid=lo+hi
if key<a[mid]:
hi=mid-1
elif key>a[mid]:
lo=mid+1
else:
return mid
return -1
if __name__=="__main__":
print(Find(key,f))