C++ 二分法
二分法广泛应用在这个领域,合理使用二分法能将O(n)算法变成O(logn),但是写好二分法,也需要一定的练习。
如如何控制递归结束条件。
如果保证最后一位数和第一位数也能被检索得到。
1.二分法查找递增序列
代码如下(示例):
int binary_search(int a[], int s, int t, int x) {
//这个写出来也需要很多功力的,如递归终止条件,和划分情况。
//不好把握,多练习练习。最重要的是最后的几步,能不能全覆盖。
if (s > t) {
return -1;
}
int temp = (s + t) / 2 ;// cout << temp << endl;
if (a[temp] == x) {
return temp+1;
}
else if (a[temp] > x)
binary_search(a, s, temp - 1, x);
else
binary_search(a, temp + 1, t, x);
}
void main() {
int n = 10;
int a[] = { 1, 2, 3, 5, 7, 8, 9, 15, 17, 19 };
for (int j = 0; j < 20; j++)
cout << binary_search(a, 0, 9, j) << endl;;
}
总结
二分法应用广泛,一定要多多练习。