The following example shows how to use the permutation p to print the elements of the vector v in ascending order,
gsl_sort_vector_index (p, v); for (i = 0; i < v->size; i++) { double vpi = gsl_vector_get(v, p->data[i]); printf("order = %d, value = %g\n", i, vpi); }
The next example uses the function gsl_sort_smallest
to select
the 5 smallest numbers from 100000 uniform random variates stored in an
array,
#include <gsl/gsl_rng.h> #include <gsl/gsl_sort_double.h> int main (void) { const gsl_rng_type * T; gsl_rng * r; int i, k = 5, N = 100000; double * x = malloc (N * sizeof(double)); double * small = malloc (k * sizeof(double)); gsl_rng_env_setup(); T = gsl_rng_default; r = gsl_rng_alloc (T); for (i = 0; i < N; i++) { x[i] = gsl_rng_uniform(r); } gsl_sort_smallest (small, k, x, 1, N); printf("%d smallest values from %d\n", k, N); for (i = 0; i < k; i++) { printf ("%d: %.18f\n", i, small[i]); } return 0; }
The output lists the 5 smallest values, in ascending order,
$ ./a.out 5 smallest values from 100000 0: 0.000005466630682349 1: 0.000012384494766593 2: 0.000017581274732947 3: 0.000025131041184068 4: 0.000031369971111417