// Source File: binsearch2.C // // This program demonstrates the recursive // version of Binary Search // // Author: Alan Baumgarten // Date: March 10, 1999 #include int BinSearch (int array[], int low, int high, int value); int main() { int num[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int pos; pos = BinSearch (num, 0, 9, 3); if (pos == -1) { cout << "Didn't find 3" << endl; } else { cout << "Found 3 at position " << pos << endl; } pos = BinSearch (num, 0, 9, 23); if (pos == -1) { cout << "Didn't find 23" << endl; } else { cout << "Found 23 at position " << pos << endl; } return 0; } // This function performs a binary search on // an array of integers. It is assumed that // the array is sorted in ascending order. // // Parameters: // array - the array to search // low - lower index of range of array to search // high - higher index of range of array to search // value - the value to search for // // Returns: // If found, the position (index) where found // If not found, -1 int BinSearch (int array[], int low, int high, int value) { int mid, test; if (low > high) { // not found return -1; } mid = (high + low) / 2; // midpoint test = array[mid]; if (test == value) { return mid; // found } else if (test < value) { return BinSearch (array, mid + 1, high, value); } else { return BinSearch (array, low, mid - 1, value); } }