编程珠玑第4章第2题
#include "stdafx.h" #include #include using namespace std; template bool IsSorted( InPtr posBegin_, InPtr posEnd_ ) { InPtr posSecond = posBegin_; ++posSecond; for( ;posSecond != posEnd_; ++posSecond) { if( *posSecond < *posBegin_ ) { return false; } ++posBegin_; } return true; } template InPtr BinarySearchFirst( InPtr posBegin_, InPtr posEnd_, const TYPE Search_ ) { int iDistance = distance(posBegin_, posEnd_); if( iDistance <= 0 ) { return posEnd_; } InPtr posLeft = posBegin_; InPtr posRight = posEnd_; InPtr posMiddle = posBegin_; advance(posMiddle, iDistance / 2); InPtr posFind; if( *posMiddle > Search_ ) { /// 当中间位较大时,在前半部寻找 posRight = posMiddle; posFind = BinarySearchFirst( posLeft, posRight, Search_ ); } else if( *posMiddle < Search_ ) { /// 当中间位较大时,在后半部寻找 posLeft = posMiddle; advance( posLeft, 1 ); posFind = BinarySearchFirst(posLeft, posRight, Search_ ); } else { /// 当找到的是第一个时,返回 if( posMiddle == posBegin_ ) { return posMiddle; } /// 当找到的前一个与当前不等时,返回 InPtr posPrev = posMiddle; advance(posPrev, -1); if( *posPrev != Search_ ) { return posMiddle; } /// 否则在前半部寻找 posRight = posMiddle; posFind = BinarySearchFirst(posLeft, posRight, Search_ ); } if( posFind != posRight ) { return posFind; } return posEnd_; } int _tmain(int argc, _TCHAR* argv[]) { vector coll; for(int i = 0; i < 20; ++i) { coll.push_back(i); } if( !IsSorted(coll.begin(), coll.end()) ) { cout << "未排序!" << endl; return 0; } vector::iterator pos; int iFind = 0; pos = BinarySearchFirst(coll.begin(), coll.end(), iFind); if( pos != coll.end() ) { cout << "在第" << distance(coll.begin(), pos) << "位发现" << "元素" << iFind << endl; } else { cout << "未找到元素" << iFind << endl; } return 0; }