Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get k-th largest values [closed]

Tags:

algorithm

I have some problem. I must add a lot of different values and just get only k-th largest in the end. How can I effectively implement that and what algorithm should I use?

like image 720
alex.seluta Avatar asked Jun 14 '26 11:06

alex.seluta


1 Answers

Algorithm:

  1. Create a binary maximum heap, and add each one of the first K values into the heap.

  2. For each one of the remaining N-K values, if it larger than the last value in the heap:

    Put it instead of the last value, and bubble it up in order to resort the heap.

  3. Extract all the (K) values from the heap into a list.


Complexity:

  1. O(K)

  2. O((N-K)×log(K))

  3. O(K×log(K))

If N-K ≥ K, then the overall complexity is O((N-K)×log(K)).

If N-K < K, then the overall complexity is O(K×log(K)).

like image 176
barak manos Avatar answered Jun 17 '26 23:06

barak manos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!