二分查找C++实现

<pre name="code" class="cpp">#include <iostream>
#include <string>
#include <vector>
using namespace std;
int binSearch(int A[], int length, int key){
	int L = 0, R = length - 1;
	while (L <= R){
		int M = (L + R) / 2;
		if (A[M]>key)
			R = M-1;
		else if (A[M] < key)
			L = M+1;
		else
			//return M;若不做处理,在有重复值的情况下,返回下标不一定为第一个。
		{
			if (A[M - 1] == key)
			{
				R = R - 1;
			}
			else{
				return M;
			}
		}
	}
	return -1;
}
void main(){
	int A[] = { 0, 1, 2, 3, 4, 4,5,5};
	cout << binSearch(A, 7,4);


}



            
原文地址:https://www.cnblogs.com/muyangshaonian/p/9650519.html