This problem is based on recurrences chapter 4, specifically on problem 4.3a.
A recursive binary search:
template<class Ptr> Ptr binsearch(Ptr p, Ptr b, Ptr e) /* Pre: p points to desired item (somewhere in mem). b and e define the sorted range of mem in which to search. b < e is required. We assume standard comparison operators can be used on the datatype pointed to by Ptr instances. Post: Return ptr to occurrence of *p in sorted array *[b..e). Return NULL if no such value exists. */ { if (e - b == 1) if (*p == *b return b; // successful search else return NULL; // failed search else { Ptr m = b + (e - b)/2; if (*p < *m) return binsearch(p, b, m); else return binsearch(p, m, e); } }
Professor Stu Bjorn prefers the old method of array and index parameters instead of pointers. Stu writes this equivalent code:
template<class V> size_t binsearch(V& x, V A[], size_t b, size_t e) /* Pre: x is the desired item. A is a sorted array (using 1-based indexing). b and e define the sorted range in which to search. b < e is required. We assume standard comparison operators can be used on datatype V. Post: Return location of occurrence of x in sorted array [A[b]..A[e]). Return 0 if no such value exists (a not valid array index). */ { if (e - b == 1) if (x == A[b]) return b; // successful search else return 0; // failed search else { size_t m = (b + e)/2; if (x < A[m]) return binsearch(x, A, b, m) ; else return binsearch(x, A, m, e); }
To say f(n) is "about" g(n) means that f(n)/g(n) --> 1, as n --> infinity.