When it comes to big O notation - no, it cannot be done better. Finding an arbitrary element in a max heap is O(n)
.
You could however reduce the number of maximum nodes you need to traverse to 1/2 * n
, and essentially double the speed of the algorithm. [still O(n)
domain], since the 2nd smallest element in a max heap has at most one son, so you can traverse only leaves (n/2 of those), and one element at most which has only one son. (remember, a binary heap is an array representing a complete tree, thus at most one element has exactly one son).
One can also enhance a bit the removal step, but I doubt it will have any significant affect), so I wouldn't bother putting effort into it.