/* File: bsearch1.cpp A binary search function for a sorted array that we wrote in class. */ #include #include using namespace std ; // Use binary search to look for stuff in array A[start], .., A[end] // inclusive. Returns the index i such that A[i] == stuff or // returns -1 if not found. // int bsearch(int A[], int start, int end, int stuff) { int middle ; while (start <= end) { // assert(start <= end) ; middle = ( start + end ) / 2 ; assert (start <= middle && middle <= end) ; if ( A[middle] == stuff) { return middle ; } else if ( A[middle] < stuff ) { start = middle + 1 ; } else { end = middle - 1 ; } } // end of while ( ... ) return -1 ; } int main() { int A[15] = { 2, 5, 6, 9, 10, 12, 14, 17, 21, 32, 39, 41, 44, 45, 60 } ; int result ; result = bsearch(A, 0, 14, 41) ; if (result == -1) { cout << "41 is not in array A[].\n" ; } else { cout << "41 is in A[" << result << "]\n" ; } result = bsearch(A, 0, 14, 23) ; if (result == -1) { cout << "23 is not in array A[].\n" ; } else { cout << "23 is in A[" << result << "]\n" ; } cout << "\n\n" ; int plusOne ; for (int i=0 ; i < 15 ; i++) { result = bsearch(A, 0, 14, A[i]) ; if (result == -1) { cout << A[i] << " is not in array A[].\n" ; } else { cout << A[i] << " is in A[" << result << "]\n" ; } plusOne = A[i] + 1 ; result = bsearch(A, 0, 14, plusOne) ; if (result == -1) { cout << plusOne << " is not in array A[].\n" ; } else { cout << plusOne << " is in A[" << result << "]\n" ; } } return 0 ; }