mercredi 6 juillet 2016

Sort an array in place according to a sort order defined in another array

I have an array that defines the sort order for another array. For example, to sort an array consisting of char * data[] = {"c", "b", "a"};, the sort_order array would be {2, 1, 0} - when the array is sorted, the first element should be "c" (which is data[sort_order[0]]).

(The background for this is that I have two arrays which I want to sort, but the second array should use the same sort order as the first one. So basically I sort {0, 1, 2} using the values from the first array, and then I'd use this sort order to sort the actual values of both arrays.)

The obvious solution would be to create a copy of the array (new_data), and then assign every element the correct value as defined by the sort order:

for (int i = 0; i < n; ++i)
{
    new_data[i] = data[sort_order[i]];
}

However, this requires making a copy of the array. Is there a way I can swap the elements of the original array to sort them in place without having to copy the array?

Edit: The "possible duplicate" does use another array, which is precisely what I am trying to avoid.

Aucun commentaire:

Enregistrer un commentaire