lundi 25 mai 2015

m smallest values of vector with size n, c++11

I need the average of the nClose smallest value (except the first zero) in a vector with n elements where we know that nClose + 1 < n, there are only non-negative numbers, and the vector contains at least one zero value. Furthermore, nClose will be a lot smaller than n, say that nClose will be around 10 and n will be around 500.

Normally I will use min_element to find the minimum, however this is useless here since I need several values. At the moment I use the following code

sort(diff.begin(), diff.end());
double sum = accumulate(diff.begin() + 1, diff.begin() + 1 + nClose, 0);
double avg = sum / nClose;

Due to the sort it runs in O(n log n) where we can do it in O(nClose*n) by just find the minimum and remove it, then repeat this for nClose times. Know one of you how to accomplish this with the algorithms of c++11?

Aucun commentaire:

Enregistrer un commentaire