折半查找非递归与递归实现:
#include<stdio.h>
int linner(int a[],int n,int value);
int halfSearch(int a[],int n,int value);
int halfSearch2(int a[],int n,int value,int left,int right);
void main()
{
int a[8]= {12,34,50,53,123,135,167,189};
int num=halfSearch2(a,8,167,0,7);
if(num==-1)
printf("没有找到这个数");
else
printf("位置在第:%d",num);
}
int linner(int a[],int n,int value)
{
for(int i=0; i<n; i++)
if(a[i]==value)
return i+1;
return -1;
}
int halfSearch(int a[],int n,int value)
{
int left=0,right=n-1,mid;
while(left<=right)
{
mid=(left+right)/2;
if(value>a[mid])
left=mid+1;
else if(value<a[mid])
right=mid-1;
else
return mid+1;
}
return -1;
}
int halfSearch2(int a[],int n,int value,int left,int right)
{
if(left>right)
return -1;
int mid=(left+right)/2;
if(a[mid]==value)
return mid+1;
else if(value>a[mid])
return halfSearch2(a,n,value,mid+1,right);
else
return halfSearch2(a,n,value,left,mid-1);
}