(C++)二分查找法

//二分查找法(左闭右闭写法)
int binarySearch(vector<int>arr, int target) {
	sort(arr.begin(), arr.end()); //使用二分查找法的前提是数组有序
	int l = 0;
	int r = arr.size() - 1;
	while (l <= r) {
		int mid = (r - l) / 2 + l; //防止溢出
		if (target > arr[mid]) l = mid + 1;
		else if (target < arr[mid]) r = mid - 1;
		else return mid;
	}
	return -1;
}

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