Created
August 24, 2013 03:15
-
-
Save PhDP/6325846 to your computer and use it in GitHub Desktop.
If variance is great, summing the values of an array can be problematic. The problem can often be solved by sorting the array before summing.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
double sum_d(const double *x, size_t length) { | |
double sum = 0.0; | |
for (size_t i = 0; i < length; ++i) { | |
sum += x[i]; | |
} | |
return sum; | |
} | |
double srtsum_d(const double *x, size_t length) { | |
// Copy the array & sort it with quicksort. | |
double *sorted = (double*)malloc(length * sizeof(double)); | |
memcpy((void*)sorted, (void*)x, length * sizeof(double)); | |
qsort((void*)sorted, length, sizeof(double), compare_double_asc); | |
const double sum = sum_d(sorted, length); // The actual answer | |
free(sorted); // Free memory | |
return sum; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment