#include using namespace std; /* * Searches the array anArray[first] through anArray[last] * for value by using a binary search. * @pre 0 <= first, last <= SIZE - 1, where SIZE is the * maximum size of the array, and anArray[first] <= * anArray[first + 1] <= ... <= anArray[last]. * @post None. * @param anArray The array to search. * @param first The low index to start search from. * @param last The high index to stop searching at. * @param value The search key. * @return If value is in anArray, the function returns the * index of the array item that equals value; * otherwise the function returns -1. */ int binarySearch(const int anArray[], int first, int last, int value) { int index; if (first > last) index = -1; // value not in original array else { int mid = (first + last)/2; if (value == anArray[mid]) index = mid; // value found at anArray[mid] else if (value < anArray[mid]) index = binarySearch(anArray, first, mid-1, value); else index = binarySearch(anArray, mid+1, last, value); } return index; } int main() { int index; int array[] = {2, 5, 7, 8, 9, 34, 54, 91, 103, 104, 999, 1062, 3387}; cout << "Array is: "; for(int i=0 ; i<13 ; i++) cout << array[i] << " "; cout << endl; cout << "Search for 2: "; if((index = binarySearch(array, 0, 13, 2)) >= 0) cout << "Found at index " << index; else cout << "Not found"; cout << endl; cout << "Search for 56: "; if((index = binarySearch(array, 0, 13, 56)) >= 0) cout << "Found at index " << index; else cout << "Not found"; cout << endl; cout << "Search for 91: "; if((index = binarySearch(array, 0, 13, 91)) >= 0) cout << "Found at index " << index; else cout << "Not found"; cout << endl; return 0; }