Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a sorting-algorithm worth implementing here?

Tags:

c++

sorting

I have a list of positive integers, and I want to store the 3 biggest values in the variables h1, h2, and h3. The remaining values are irrelevant.

I considered managing them with an int* and reallocating memory as it is filled, followed by a suitable sorting algorithm, but is it really worth it? Since I don't really need to sort the entire array, I just did it like this:

if (currentVal > h3) {
    h3 = currentVal;
    if (currentVal > h2) {
        h3 = h2;
        h2 = currentVal;
        if (currentVal > h1) {
            h2 = h1;
            h1 = currentVal;
        }
    }
}

It feels like a dumb and static way of doing it, but it works. Should I implement a sorting algorithm instead, and if yet, any suggestion what might be suitable?

like image 899
krystah Avatar asked Jul 01 '26 13:07

krystah


1 Answers

For "top 3", that's perfectly reasonable. For "top k" with a larger (but fixed) value for k, you might want to try using a priority queue.

like image 70
rici Avatar answered Jul 03 '26 05:07

rici