#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 rec_bsearch(int A[], int start, int end, int stuff) ; 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 ; } // Note: linear search is much slower than binary search. // int linear_search(int A[], int start, int end, int stuff) { for (int i=start ; i<=end ; i++) { if (A[i] == stuff) return i ; } return -1 ; } // Call recursive binary search, non-recursive binary search // or linear search, depending. Still gets the job done. // int weird_search(int A[], int start, int end, int stuff) { if ( (start%2 == 0) && (end%2 == 0) ) { return bsearch(A,start,end,stuff) ; } else if ( (start%2 == 1) && (end%2 == 1) ) { return linear_search(A,start,end,stuff) ; } else { return rec_bsearch(A,start,end,stuff) ; } } // This version calls weird_search(). // It might end up recursively calling itself, or not. // It doesn't matter for correctness. // (It can affect the running time, though.) // int rec_bsearch(int A[], int start, int end, int stuff) { int middle ; if (start > end) return -1 ; middle = ( start + end ) / 2 ; if ( A[middle] == stuff ) return middle ; if ( A[middle] < stuff ) { return weird_search(A, middle + 1, end, stuff) ; } else { return weird_search(A, start, middle - 1, stuff) ; } } int main() { int A[15] = { 2, 5, 6, 9, 10, 12, 14, 17, 21, 32, 39, 41, 44, 45, 60 } ; int result ; result = rec_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 = rec_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 = rec_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 = rec_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 ; }