二分查找法
Posted darklights
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找法相关的知识,希望对你有一定的参考价值。
一、
#include <iostream> #include <cassert> #include <ctime> using namespace std; template<typename T> int binarySearch(T arr[], int n, T target){ int l = 0, r = n-1; while( l <= r ){ int mid = l + (r-l)/2; if( arr[mid] == target ) return mid; if( arr[mid] > target ) r = mid - 1; else l = mid + 1; } return -1; } int main() { int n = 1000000; int* a = new int[n]; for( int i = 0 ; i < n ; i ++ ) a[i] = i; clock_t startTime = clock(); for( int i = 0 ; i < 2*n ; i ++ ){ int v = binarySearch(a, n, i); if( i < n ) assert( v == i ); else assert( v == -1 ); } clock_t endTime = clock(); cout << "Binary Search (Without Recursion): " << double(endTime - startTime) / CLOCKS_PER_SEC << " s"<<endl; delete[] a; return 0; }
二、
以上是关于二分查找法的主要内容,如果未能解决你的问题,请参考以下文章