互联网校招常考经典算法模板汇总(java && )

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/NCUscienceZ/article/details/84032950

一、二分查找
1、左闭右闭版[start, end]
(1)循环实现:

bool binarySearch(int arr[ ], int start, int end, int target){
	while(start<=end){//左闭右闭是小于等于
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) end = mid-1; 
			 else start = mid+1;
	}
	return false;
}

(2)递归实现:

bool binarySearch(int arr[ ], int start, int end, int target){
	if (start<=end){//左闭右闭是小于等于
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) return binarySearch(arr, start, mid-1, target);
			 else return return binarySearch(arr, mid+1, end, target);
	}else return false;
}

2、左闭右开版[start, end)
(1)循环实现:

bool binarySearch(int arr[ ], int start, int end, int target){
	while(start<end){//左闭右开是小于
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) end = mid; //多减1错误
			 else start = mid+1;//不加1容易死循环
	}
	return false;
}

(2)递归实现:

bool binarySearch(int arr[ ], int start, int end, int target){
	if (start<end){//左闭右闭是小于等于
		int  mid = (start+end)/2;
		int  t = arr[mid];
		if (t == target) return ture;
		else if (t > target) return binarySearch(arr, start, mid, target);
			 else return return binarySearch(arr, mid+1, end, target);
	}else return false;
}

猜你喜欢

转载自blog.csdn.net/NCUscienceZ/article/details/84032950