二分查找

//二分查找 INIT:a[]

bool   BinSearch(int *a,int low,int high,int target){  //a数组递增;
	while(low<=high){
		int mid=(low+high)/2;
		if(a[mid]==target) return true;
		if(a[mid]>target) high=mid-1;
		else  low=mid+1;
	}
    return false;
}

//找到一个位置使右边的数>=此位的数 INIT:arr[]

int  BSearchUpperBound(int  arr[], int low, int high, int target){ 
    while(low<=high){
		int mid = (low+high)/2;
		if(arr[mid]>=target) high=mid-1;
		if(arr[mid]<target) low=mid+1;
     }
     return low-1;
}

  

posted on 2013-08-13 21:28  Amyc  阅读(87)  评论(0编辑  收藏  举报