// ---- function definition for binary search ---- // precondition: // if n is the size of array a, first and last are both // in the range 0 .. n-1 // a is sorted (i.e., elements are in nondescending order) // postcondition: // if x is in a[first] .. a[last], return value is index of // element that matches x // otherwise return value is -1 int binsearch(const int a[], const int first, const int last, const int x) { if (first > last) return -1; else { int mid = (first + last) / 2; if (x == a[mid]) return mid; else if (x < a[mid]) return binsearch(a, first, mid-1, x); else // (x > a[mid]) return binsearch(a, mid+1, last, x); } }