cpp-algo-cases/chapter_divide_and_conquer/binary_search_recur.cpp

46 lines
1.0 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: binary_search_recur.cpp
* Created Time: 2023-07-17
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD>ֲ<EFBFBD><D6B2>ң<EFBFBD><D2A3><EFBFBD><EFBFBD><EFBFBD> f(i, j) */
int dfs(vector<int> &nums, int target, int i, int j) {
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ϊ<EFBFBD>գ<EFBFBD><D5A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>Ŀ<EFBFBD><C4BF>Ԫ<EFBFBD>أ<EFBFBD><D8A3>򷵻<EFBFBD> -1
if (i > j) {
return -1;
}
// <20><><EFBFBD><EFBFBD><EFBFBD>е<EFBFBD><D0B5><EFBFBD><EFBFBD><EFBFBD> m
int m = (i + j) / 2;
if (nums[m] < target) {
// <20>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(m+1, j)
return dfs(nums, target, m + 1, j);
} else if (nums[m] > target) {
// <20>ݹ<EFBFBD><DDB9><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(i, m-1)
return dfs(nums, target, i, m - 1);
} else {
// <20>ҵ<EFBFBD>Ŀ<EFBFBD><C4BF>Ԫ<EFBFBD>أ<EFBFBD><D8A3><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
return m;
}
}
/* <20><><EFBFBD>ֲ<EFBFBD><D6B2><EFBFBD> */
int binarySearch(vector<int> &nums, int target) {
int n = nums.size();
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> f(0, n-1)
return dfs(nums, target, 0, n - 1);
}
/* Driver Code */
int main() {
int target = 6;
vector<int> nums = {1, 3, 6, 8, 12, 15, 23, 26, 31, 35};
// <20><><EFBFBD>ֲ<EFBFBD><D6B2>ң<EFBFBD>˫<EFBFBD><CBAB><EFBFBD><EFBFBD><EFBFBD>
int index = binarySearch(nums, target);
cout << "Ŀ<EFBFBD><EFBFBD>Ԫ<EFBFBD><EFBFBD> 6 <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> = " << index << endl;
return 0;
}