C ++ binary search

Return type bool:

. 1 Template < class T> static  BOOL binarySearch (T * S, T const & E, int LO, int Hi) {
 2      the while (LO < Hi) {
 . 3          int mi The = (LO + Hi) >> . 1 ;
 . 4          E <S [mi the] = mi the Hi:? = mi the LO + . 1 ;
 . 5      }
 . 6      return S [- LO] == e; // this method returns a failure to find the rank is not greater than e, 
7 }

Masters code is not only simple but also beautiful!

The return value is not less than the value of the rank of finding elements:

. 1 Template < class T> static  int binarySearch (T * S, T const & E, int LO, int Hi) {
 2      the while (LO < Hi) {
 . 3          int mi The = (LO + Hi) >> . 1 ;
 . 4          E <S [mi the] = mi the Hi:? = mi the LO + . 1 ;
 . 5      }
 . 6      return --lo; // this method returns the lookup fails e is not larger than the rank of 
7 }

 

Guess you like

Origin www.cnblogs.com/MasterYan576356467/p/11209481.html