Fundamental Algorithms Analysis (007)-Binary Search[二分查找][C++/Java]

Binary Search

We provide an easy binary search algorithm here as a reference for further usage. We mentioned the binary search before and emphasized its significance and efficiency

Plain version(c++)

int binarySearch(int* arr,int len, int target) {
	int l = 0, r = len - 1, m = (l + r) / 2;
	while (l < r) {
		if (r - l == 1) return arr[r] == target ? r : arr[l] == target?l:-1;
		else {
			if (arr[m] == target) return m;
			else arr[m] < target? (l = m, m = (l + r) / 2):(r = m, m = (l + r) / 2);
		}
	}
}

You can try to implement all the algorithms I mentioned in my FAA(Fundamental Algorithms Analysis) series in other programming languages. That must be fascinating! However, why I choose C++ to do all of these? It’s a sort of feelings.

Main test

#include 
using namespace std;
int binarySearch(int* arr,int len, int target) { // Old problem, how to remove the length as a parameter? How?(when array type should be kept as a pointer)
	int l = 0, r = len - 1, m = (l + r) / 2;
	while (l < r) {
		if (r - l == 1) return arr[r] == target ? r : arr[l] == target?l:-1;// Reach the last step. This means the bound
		else {
			if (arr[m] == target) return m; // Get answer smoothly
			else arr[m] < target? (l = m, m = (l + r) / 2):(r = m, m = (l + r) / 2);// Faild to find and do next round
		}
	}
}
int main() {
	int a[] = { 1,3,5,6,8, 10,15,36,94};
	int len = end(a) - begin(a);
	cout << binarySearch(a, len, 15);//6
}

你可能感兴趣的:(c++,算法)