Consider the following binary search code:
/** * Performs the standard binary search using two comparisons per level. * Returns index where item is found or -1 if not found. */ 1. template <typename Comparable> 2. int binarySearch( const vector <Comparable> & a, const Comparable & x ) 3. { 4. int low=0; 5. int high= a.size( ) - 1; 6. 7. while( low <= high ) { 8. int mid=(low + high ) / 2; 9. if( a[mid]<x) { 10. low = mid+ 1; 11. } else if( a[ mid ]>x) { 12. high = mid - 1; 13. } else { 14. return mid; 15. } 16. } 17. return NOT_FOUND; // NOT_FOUND defined as -1 18. }
Get Free Quote!
303 Experts Online