二分搜索算法(递归和非递归实现)

//循环迭代方法
int binIteration(int a[],int low,int high,int key){
	if(low>high) return -1;
	if(a[high] < key || a[low] > key) return -1;
	while(low<=high){
		int mid=(low+high)/2;
		if(a[mid] == key) return mid;
		else if(a[mid] > key) high = mid-1;
		else low = mid+1;
	}
	return -1;
}

//递归方法
int binRecursion(int a[],int low,int high,int key){
	if(low > high) return -1;
	if(a[high] < key || a[low] >key) return -1;
	int mid=(low+high)/2;
	if(a[mid] == key) return mid;
	else if(a[mid] > key) return binRecursion(a,low,mid-1,key);
	else return binRecursion(a,mid+1,high,key);
}

你可能感兴趣的:(二分搜索算法(递归和非递归实现))