是一个排序算法值得实现吗? [英] Is a sorting-algorithm worth implementing here?
问题描述
我有一个正整数列表,我想存储变量 h1
, h2
和 h3
。
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.
我考虑用 int *
和
填充内存,然后是合适的排序算法,但它是真的值得吗?因为我不需要整个数组排序,我只是这样:
I considered managing them with an int*
and realloc
ating 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?
推荐答案
对于top 3,我应该使用一个排序算法,这是完全合理的。对于 k
的值较大(但固定)的top k,您可能需要尝试使用优先级队列。
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.
这篇关于是一个排序算法值得实现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!