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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With