Related: priority queue with limited space: looking for a good algorithm
I am looking for an algorithm which returns the k-largest elements from a list, but does not change the order of the k-largest elements, e.g. for k=4
and given 5,9,1,3,7,2,8,4,6
, the algorithm should return 9,7,8,6
.
More background, my input data are approximately 200 pairs (distance,importance)
which are ordered w.r.t distance
, and I need to select the 32 most important of them. Performance is crucial here, since I have to run this selection algorithm a few thousand times.
Up to now I have the two following ideas, but both of them seem not to be the best possible.
- Remove the minimum element iteratively until 32 elements are left (i.e. do selection sort)
- Use quickselect or median-of-medians to search for the 32nd largest element. Afterwards, sort the remaining 31 elements again w.r.t. distance.
I need to implement this in C++, so if anybody wants to write some code and does not know which language to use, C++ would be an option.