// Source File: binsearch.C // // This program demonstrates the iterative // version of Binary Search // // Author: Alan Baumgarten // Date: March 10, 1999 #include int BinSearch (int array[], int num_elems, int value); int main() { int num[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; int pos; pos = BinSearch (num, 10, 3); if (pos == -1) { cout << "Didn't find 3" << endl; } else { cout << "Found 3 at position " << pos << endl; } pos = BinSearch (num, 10, 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 // num_elems - number of elements in the array // value - the value to search for // // Returns: // If found, the position (index) where found // If not found, -1 int BinSearch (int array[], int num_elems, int value) { int low = 0, high = num_elems - 1; int mid, test; while (low <= high) { mid = (high + low) / 2; // midpoint test = array[mid]; if (test == value) { return mid; // found } else if (test < value) { low = mid + 1; // look to "right" } else { high = mid - 1; // look to "left" } } return -1; // not found }