This problem is based on the heaps discussion in CLR section 6.1
Let A be a min-heap of size n > 4 made from a set of n distinct values. For this problem we'll discuss positions indexed starting at 1, so the range of indices is [1..n]. Position 1 holds the root and the children of node i (if any) are at at positions 2i and 2i + 1. The rank r value in a set of n distinct values is the value that would be in position r if the data were sorted, so r-1 values are smaller and n-r are larger.
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) /* p points to desired item. b and e define the sorted range in which to search. Return ptr to occurrence of *p in sorted array *[b..e). Return e if no such value exists. We assume standard comparison operators can be used on the datatype pointed to by Ptr instances. */ { if (e <= b) return e; // failed search if (*p == *b return b; // successful search Ptr m = b + (e - b)/2; return (*p < *m) ? binsearch(p, b, m) : 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) /* x is the desired item. A is a sorted array. b and e define the sorted range in which to search. Return location of occurrence of x in sorted array [A[b]..A[e]). Return 0 if no such value exists (1-based indexing). We assume standard comparison operators can be used on datatype V. */ { if (e <= b) return 0; // failed search if (x == A[b] return b; // successful search size_t m = (b + e)/2; return (x < A[m]) ? binsearch(x, A, b, m) : binsearch(x, A, m, e); }