二分查找算法(少儿编程)

int binaryFind(int sz[], int start, int end, int x){
	int mid = (start+end)/2;
	if(sz[mid] > x){
		end = mid-1;
	}
	else if(sz[mid] < x){
		start = mid+1;
	}
	else{
		return mid;
	}
	binaryFind(sz,start,end,x);
}

int main() {
	int sz[20]={1,2,3,4,5,6,7,8,9,10,13,14,16,17,18,22,23,25,26,28};
	cout<

 

 


int binaryFind2(int sz[], int start, int end, int x){
	int mid = (start+end)/2;
	while(start <= end){
		mid = (start+end)/2;
		if(sz[mid] < x){
			start = mid+1;
		}
		else if(sz[mid] >x){
			end = mid -1;
		}
		else{
			return mid;
		}
	}
	return -1;
}

 

你可能感兴趣的:(少儿编程)