Listing 8 Illustrates how to construct an index for an array of integers

/* index1.c: Sort indirectly via an index */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NELEMS 4

static int comp(const void *, const void *);

static int some_ints[NELEMS] = {40,12,37,15};

main()
{
   size_t i;
   size_t idx[NELEMS] = {0,1,2,3};

   qsort(idx,NELEMS,sizeof idx[0],comp);

   printf("Sorted array:\n");
   for (i = 0; i < NELEMS; ++i)
      printf("%d\n",some_ints[idx[i]]);

   printf("\nOriginal array:\n");
   for (i = 0; i < NELEMS; ++i)
      printf("%d\n",some_ints[i]);
   return 0;
}

static int comp(const void *pl, const void *p2)
{
   size_t i = * (size_t *) pl;
   size_t j = * (size_t *) p2;

   return some_ints[i] - some_ints[j];
}
/* Output:
Sorted array:
12
15
37
40
Original array:
40
12
37
15
*/
/* End of File */