If we have sorted arrays we can achieve the same searching speed as from an optimally constructed binary search tree using a recursive search that looks for a specific value somewhere between two array positions:
search(arr[], int lower, int upper, int key) if (lower > upper) we've run out of positions to search, return false else midpoint = (lower+upper)/2 if the midpoint contains the key we've found it, return true otherwise if the value in the midpoint is bigger than the key then the key must be between positions lower and midpoint-1 so make a recursive call on that segment otherwise the key must be between positions midpoint+1 and upper so make a recursive call on that segmentThis is illustrated in the code below.
// use binary search between array positions lower and upper, // seeking the key value specified by id // return the position if found, -1 otherwise int bsearch(int arr[], int lower, int upper, int id) { // make sure the recursion stops eventually, // returning -1 to indicate we never found the id if (lower > upper) return -1; // compute the midpoint of the segment we're searching int midpoint = (lower + upper) / 2; // see if the midpoint matches the id we're looking for if (arr[midpoint] == id) return midpoint; // otherwise recursively search *either* the lower or upper // half of the segment for the id we want else if (arr[midpoint] > id) return bsearch(arr, lower, midpoint-1, id); else return bsearch(arr, midpoint+1, upper, id); }