非递归实现
代码
#include <stdio.h>
int search(int num[],int n,int key)
{
int low=0;
int high =n-1;
int mid=0;
while(low<=high)
{
mid = (low+high)/2;
if(num[mid]==key)return mid;
else if(num[mid]<key)
{
low=mid+1;
}
else
{
high = mid-1;
}
}
return -1;
}
int main()
{
int a;
scanf("%d",a);
int num[10]={0,1,2,3,4,5,6,7,8,9};
printf("%d\n",search(num,10,a));
return 0;
}
int search(int num[],int n,int key)
{
int low=0;
int high =n-1;
int mid=0;
while(low<=high)
{
mid = (low+high)/2;
if(num[mid]==key)return mid;
else if(num[mid]<key)
{
low=mid+1;
}
else
{
high = mid-1;
}
}
return -1;
}
int main()
{
int a;
scanf("%d",a);
int num[10]={0,1,2,3,4,5,6,7,8,9};
printf("%d\n",search(num,10,a));
return 0;
}
递归实现
代码
#include <stdio.h>
int search(int num[],int low,int high,int key)
{
if(low==high&&num[low]!=key)
{
return -1;
}
int mid=0;
mid = (low+high)/2;
if(num[mid]==key)
{
return mid;
}
else if(num[mid]<key)
{
low =mid+1;
}
else
{
high =mid-1;
}
search(num,low,high,key);
}
int main()
{
int num[10]={0,1,2,3,4,5,6,7,8,9};
printf("%d\n",search(num,0,9,0));
return 0;
}
int search(int num[],int low,int high,int key)
{
if(low==high&&num[low]!=key)
{
return -1;
}
int mid=0;
mid = (low+high)/2;
if(num[mid]==key)
{
return mid;
}
else if(num[mid]<key)
{
low =mid+1;
}
else
{
high =mid-1;
}
search(num,low,high,key);
}
int main()
{
int num[10]={0,1,2,3,4,5,6,7,8,9};
printf("%d\n",search(num,0,9,0));
return 0;
}