#ifndef _BINARYSEARCH_H_ #define _BINARYSEARCH_H_ template< class T > int binarysearch( T * lpArr, const T & v, int num ) { //lpArr指向从小到大排列的数组 int iStart = 0; int iEnd = num - 1; int iMid = 0; if( ( v > lpArr[ iEnd ] ) || ( v < lpArr[ iStart ] ) ) { return -1; } while( true ) { iMid = ( iStart + iEnd ) / 2; if( v == lpArr[ iMid ] ) { return iMid; } if( v < lpArr[ iMid ] ) { iEnd = iMid; } else { iStart = iMid + 1; } if( iStart == iEnd ) { if( v == lpArr[ iStart ] ) { return iStart; } else { return -1; } break; } } return -1; } #endif 这个例子是使用二分查找法在一个n个元素的集合里面查找是否存在两个和为10的元素,是的话在控制台打印“find!“这是《算法导论》中的题目,符合题目要求,使最坏情况下运行时间为O( nlgn ) #include<iostream> using namespace std; #include<conio.h> #include"binarysearch.h" int main() { int a[ 8 ] ={ 2, 4, 5, 6, 4, 56, 77, 89 }; for( int i = 0; i < 8; ++i ) { cout<<a[ i ]<<" "; } cout<<endl; for( int i = 0; i < 8; ++i ) { int temp = 10 - a[ i ]; if( binarysearch( a, temp, 8 )>= 0 ) { cout<<"find!"<<endl; break; } } getch(); return 0; }