In situations when you have to perform a synchronized rearrangement of several independent data structures you can follow one of the two approaches:
- An intrusive "internal" approach, mentioned by @wallyk - i.e. provide your own swap function that will swap elements in all three arrays synchronously.
- A non-intrusive "external" approach - decompose the sorting procedure into two independent steps: first, generate the sorting permutation from the "main" array, then independently apply that sorting permutation to each of the three arrays.
The first approach might be easier to implement, but it has some obvious drawbacks. As the number of data sets grows and/or elements themselves become heavier, the swap function becomes heavier as well. This is not a good thing for sorting algorithms based on physical copying of elements, since such algorithms might relocate (swap) each element more than once.
The second approach is inherently based on indirect, indexed sorting, meaning that it is less sensitive to how heavy element copying is. The second approach copies each of the actual elements only once, when it knows its final position.
To generate the sorting permutation all you need to do is to take an integer index array p
initialized with { 0, 1, 2, 3, ... }
. Instead of directly sorting values1
, sort this index array p
to make it produce the proper ordering for your values1
array. (Standard qsort
function does not work very well for such applications, since it is contextless.)
After sorting, that index array will serve as your permutation. All you need to do is to rearrange each of your three arrays in accordance with that permutation. It can be done in-place or, easier, out-of-place, depending on what you need.
In your specific example, you will start with index array
p = { 0, 1, 2, 3, 4, 5 }
After sorting it will turn into
p = { 5, 1, 4, 0, 3, 2 }
This is a so-called from-permutation for your values1
array: it tells you that in order to obtain a sorted version of values1
, element at position i
shall be taken from values1[p[i]]
. Now, all you need to do is to generate the rearranged versions of values1
, values2
and values3
using the same from-permutation p
.
Again, the latter step is easy to do out-of-place and is more difficult to do in-place. Here you can find some relevant implementations of in-place rearrangement for from-permutations: In-place array reordering?