/*算法总结 二分查找法: 二分查找法的前提是数据已经排序,时间平均复杂度为 O(lgn) 欢迎转载,转载请注明作者 openxmpp@163.com */ #include <iostream> #include <stdio.h> using namespace std; #include <vector> using std::vector; #include <algorithm> /** * @brief binarySearch 二分查找 * @param array 排序后的数组 * @param value 待查找的参数 * @return true on success ,false on failure */ template<typename T> bool binarySearch(vector<T> &array,T value) { int low = 0; int high = array.size () -1; while ( low <= high ) { int middle = ( low + high ) /2; if ( array[middle] == value ) { return true; } else if ( array[middle] > value ) { high = middle - 1; } else if ( array[middle] < value ) { low = middle + 1; } } return false; } void unitTest() { vector<int> vec; for ( int i = 0 ; i < 100 ; i += 2 ) { vec.push_back (i); } bool result = binarySearch<int>(vec,29); cout << "search result for [29] " << result<<endl; result = binarySearch<int>(vec,16); cout << "search result for [16] " << result<<endl; vector<string> strVect; strVect.push_back ("world"); strVect.push_back ("hello"); strVect.push_back ("b"); strVect.push_back ("a"); strVect.push_back ("i love cpp"); sort(strVect.begin (),strVect.end ()); result = binarySearch<string>(strVect,"notfind"); cout << "search result for [notfind] " << result<<endl; result = binarySearch<string>(strVect,"world"); cout << "search result for [world] " << result<<endl; } int main(int argc, char *argv[]) { unitTest (); return 0; }
下面是递归的实现
#include <iostream>using
二分查找法(C++ 模板实现)
最新推荐文章于 2023-10-01 11:16:40 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)