There are many strategies for your task (unless you start focusing on the self-balancing tree).
This is usually compilation speed / memory. Most algorithms require either an in-place array change or O(N) additional storage.
The self-balancing tree solution is in the latter category, but here it is not the right choice. The problem is that building the tree itself requires O(N*log N) , which will dominate the later search term and give the final complexity O(N*log N) . Therefore, you are no better than just sorting an array and using a complex data structure ...
In general, the problem largely depends on the value of i associated with N If you think for a minute, for i == 1 is this trivial right? He called the search for the maximum.
Well, the same strategy obviously works for i == 2 (carrying two max elements around) in linear time. And it is also trivially symmetrical: i.e. If you need to find the N-1st element, then just carry around two minimal elements.
However, it loses efficiency when i is about N / 2 or N / 4. Transferring the maximum elements i means sorting an array of size i ... and thus we retreat from the wall N*log N
Jerry Coffin pointed out a simple solution that is well suited for this case. Here is a link to Wikipedia . The full article also describes the median of the median method: it is more reliable, but requires more work and, as a rule, slower.
source share