I'm interested in solving Exercise 6.1-5 from the fourth edition of CLRS:
At which levels in a max-heap might the $k$th largest element reside for $2 \leq k \leq \lfloor n/2 \rfloor$, assuming that all elements are distinct?
My Attempt:
I tried solving a more specific problem of finding the possible indices $i$ for the $k$th largest element in the array representation of the heap (assuming the index of the root is 1). My approach relied on these two functions, counting the number of ancestors and descendants of the node at index $i$: $$\begin{align}\operatorname{ANCESTORS}(i,n)&=\lfloor\lg i \rfloor, \\ \operatorname{DESCENDANTS}(i,n)&=2 \left(-i 2^{\left\lfloor \lg \left(\frac{n+1}{i}\right)\right\rfloor }+ \left(i + 1\right) 2^{\left\lfloor \lg \left(\frac{n+1}{i+1}\right)\right\rfloor }-1\right)+(n+1) \left( \left\lfloor \lg \left(\frac{n+1}{i}\right)\right\rfloor -\left\lfloor \lg \left(\frac{n+1}{i+1}\right)\right\rfloor \right). \end{align}$$ Since the $k$th largest element has $k-1$ elements larger than it, we must have $$\operatorname{ANCESTORS}(i,n) \leq k-1,$$ adding $1$ to each sides, and the fact that a node's level is given by $L=\lfloor\lg i \rfloor + 1$ gives $$L \leq k. $$ On the other hand, the $k$th largest element has $n-k$ elements smaller than it, which gives the second constraint $$\operatorname{DESCENDANTS}(i,n) \leq n-k.$$ Unfortunately I couldn't extract an explicit bound for either the index $i$ or the level $L$ from this.
There are still some loose ends:
- Getting a lower bound on $i$ or at least $L$.
- Even if the bounds are available, can a partially filled max-heap always be completed in an admissible way? Maybe the upper/lower bounds do not give all possible levels?
- I also wrote some code to generate all max-heaps up to $n=16$. These data support the hypothesis that $2\leq L \leq \min(k, \lfloor \lg n \rfloor + 1)$ for $2 \leq k \leq \lfloor n/2 \rfloor$.
I would appreciate help completing this exercise. I don't think it should be too hard as this is not a starred problem. Thanks.