Assuming you have a data array A
with N
elements in it that you can't (afford to) change, you can create a parallel array P
initialized such that P[i] == i
for each element in 0..N-1. You can then arrange that the sorting algorithm permutes the array P
such that A[P[i]]
is the i
th element in the sorted order. It isn't a standard sort operation, so you'll have to write your own sort code, but it isn't a dreadfully difficult sort to write.
An alternative option is to use a parallel array of pointers. If the elements in A
are of type T
(so you have T A[N];
as the declaration of the array), then you could create a parallel array T *P[N];
and initialize each element such that P[i] == &A[i]
. Then you can sort P
using the standard qsort()
function and an appropriate comparator that follows the pointers to the values. This is arguably a better solution because it leverages the standard sorting code. Once it is sorted, you can use *P[i]
to access the i
th value in A
in sorted order, without having affected A
itself at all.