数据结构----递归算法(折半查找)

/*
	折半查找 
	查找前的数组必须是有序的 
*/
#include  
int BSearch(int a[], int x, int low, int high){
	int mid;
	if(low>high){
		return -1;	//查找失败 
	}
	mid = (low+high)/2;
	if(x==a[mid]){
		return mid;		//查找成功 
	}else if(x<a[mid]){
		return BSearch(a,x,low,mid-1);	//前半区查找 
	}else{
		return BSearch(a,x,mid-1,high);	//后半区查找 
	}
}

void main(void){
	int a[] = {1,3,4,5,17,18,31,33};
	int x = 17;
	int bn = BSearch(a,x,0,7);
	if(bn==-1){
		printf("x不在数组a中\n");
	}else{
		printf("x在数组a中,下标为:%d",bn);
	}
	getch();
} 

你可能感兴趣的:(数据结构)