NAG Library Manual, Mark 28.3
Interfaces:  FL   CL   CPP   AD 

NAG CL Interface Introduction
Example description
/* nag_sort_permute_invert (m01zac) Example Program.
 *
 * Copyright 2022 Numerical Algorithms Group.
 *
 * Mark 28.3, 2022.
 */

#include <nag.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C" {
#endif
static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b);
#ifdef __cplusplus
}
#endif

#define VEC(I, J) vec[(I)*tdvec + J]
int main(void) {
  Integer exit_status = 0, tdvec;
  NagError fail;
  double *vec = 0;
  size_t i, j, m, n, *rank = 0;

  INIT_FAIL(fail);

  /* Skip heading in data file */
  scanf("%*[^\n]");
  printf("nag_sort_permute_invert (m01zac) Example Program Results\n");
  scanf("%" NAG_UFMT "%" NAG_UFMT "", &m, &n);
  if (m >= 1 && n >= 1) {
    if (!(vec = NAG_ALLOC(m * n, double)) || !(rank = NAG_ALLOC(m, size_t))) {
      printf("Allocation failure\n");
      exit_status = -1;
      goto END;
    }
    tdvec = n;
  } else {
    printf("Invalid m or n.\n");
    exit_status = 1;
    return exit_status;
  }
  for (i = 0; i < m; ++i)
    for (j = 0; j < n; ++j)
      scanf("%lf", &VEC(i, j));
  /* nag_sort_rank_sort (m01dsc).
   * Rank sort of set of values of arbitrary data type
   */
  nag_sort_rank_sort((Pointer)vec, m, (ptrdiff_t)(n * sizeof(double)), compare,
                     Nag_Ascending, rank, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sort_rank_sort (m01dsc).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  /* nag_sort_permute_invert (m01zac).
   * Inverts a permutation converting a rank vector to an
   * index vector or vice versa
   */
  nag_sort_permute_invert(rank, m, &fail);
  if (fail.code != NE_NOERROR) {
    printf("Error from nag_sort_permute_invert (m01zac).\n%s\n", fail.message);
    exit_status = 1;
    goto END;
  }
  printf("Matrix with rows sorted according to column 1\n");
  for (i = 0; i < m; ++i) {
    for (j = 0; j < n; ++j)
      printf(" %7.1f ", VEC(rank[i], j));
    printf("\n");
  }
END:
  NAG_FREE(vec);
  NAG_FREE(rank);
  return exit_status;
}

static Integer NAG_CALL compare(const Nag_Pointer a, const Nag_Pointer b) {
  double x = *((const double *)a);
  double y = *((const double *)b);
  return (x < y ? -1 : (x == y ? 0 : 1));
}