Skip to content

Instantly share code, notes, and snippets.

@PhDP
Created August 24, 2013 03:15
Show Gist options
  • Save PhDP/6325846 to your computer and use it in GitHub Desktop.
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.
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