二分查找 c语言
#include<stdio.h>
void print_array(int *a,int n)
{
int i;
for(i=0;i<=n-1;i++)
{
printf("%d\t",a[i]);
}
printf("\n");
}
int binary_search(int *a,int n,int key)
{
int left,right,mid;
int loc;
loc=-1;
left=0;
right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(a[mid]==key)
{
loc=mid;
break;
}
if(a[mid]>key)
{
right=mid-1;
}
if(a[mid]<key)
{
left=mid+1;
}
}
return loc;
}
int binary_search_recursive(int *a,int left,int right,int key)
{
int mid;
if(left>right)
return -1;
else
{
mid=(left+right)/2;
if(a[mid]==key)
{
return mid;
}
if(a[mid]>key)
{
return binary_search_recursive(a,left,mid-1,key);
}
if(a[mid]<key)
{
return binary_search_recursive(a,mid+1,right,key);
}
}
}
int main()
{
int a[7]={1,3,5,7,9,11,13};
int num;
printf("原来数组数据为:");
print_array(a,7);
printf("请输入需要查找的数字:");
scanf("%d",&num);
printf("非递归函数求取的%d在数组a的第%d个位置,递归函数求取的%d在数组a的第%d个位置\n",num,binary_search(a,7,num)+1,num,binary_search_recursive(a,0,6,num)+1);
return 0;
}