这是一个值得实现的排序算法吗?

时间:2014-11-15 17:27:47

标签: c++ sorting

我有一个正整数列表,我想在变量h1h2h3中存储3个最大值。其余的值无关紧要。

我考虑使用int*realloc内存来管理它们,因为它已经填充,然后是一个合适的排序算法,但它真的值得吗?因为我不需要对整个数组进行排序,所以我就这样做了:

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

感觉就像一种愚蠢而静态的做法,但它确实有效。我应该改为实现排序算法,如果还有,那么任何建议可能适合吗?

2 个答案:

答案 0 :(得分:7)

对于“前三名”,这是完全合理的。对于k具有较大(但固定)值的“top k”,您可能需要尝试使用priority queue

答案 1 :(得分:2)

您可以通过以下方式在数组中找到任意数量的最大元素

#include <iostream>
#include <algorithm>
#include <functional>
#include <array>

template <size_t N> 
void n_max_element( const int a[],
                    size_t n,
                    std::array<int, N> &nmax )
{
    std::partial_sort_copy( a, a + n, 
                            nmax.begin(), nmax.end(), 
                            std::greater<int>() );
}   

int main() 
{
    const size_t N = 10;
    int a[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    std::random_shuffle( a, a + N );

    std::array<int, 3> max;

    n_max_element( a, N, max );

    std::cout << "max[0] = " << max[0] 
              << ", max[1] = " << max[1] 
              << ", max[2] = " << max[2] << std::endl;

    return 0;
}

输出

max[0] = 9, max[1] = 8, max[2] = 7