Next: , Previous: , Up: Sorting   [Index]

12.4 Computing the rank

The rank of an element is its order in the sorted data. The rank is the inverse of the index permutation, p. It can be computed using the following algorithm,

for (i = 0; i < p->size; i++) 
    size_t pi = p->data[i];
    rank->data[pi] = i;

This can be computed directly from the function gsl_permutation_inverse(rank,p).

The following function will print the rank of each element of the vector v,

print_rank (gsl_vector * v)
  size_t i;
  size_t n = v->size;
  gsl_permutation * perm = gsl_permutation_alloc(n);
  gsl_permutation * rank = gsl_permutation_alloc(n);

  gsl_sort_vector_index (perm, v);
  gsl_permutation_inverse (rank, perm);

  for (i = 0; i < n; i++)
    double vi = gsl_vector_get(v, i);
    printf ("element = %d, value = %g, rank = %d\n",
             i, vi, rank->data[i]);

  gsl_permutation_free (perm);
  gsl_permutation_free (rank);