Use qsort to sort two arrays according to one?

680 views Asked by At

If I have an array A and an Array B, is there a way to use qsort() to sort array A and, at the same time, sort all the elements of B according to the elements of A? For example, if A = { 4, 3 ,2, 1} and B = {1, 2, 3, 4}, then after the sorting they are like this:

A = {1, 2, 3, 4} and B = {4, 3, 2, 1}

1

There are 1 answers

0
adrian008 On

Assuming the question isn't duplicate, I guess you want to sort B according to the order in which it is sorted in A. I assume that A is sorted before it is sorted again. You must provide if this indeed is a valid assumption.

A very simple solution could be to identify the order in A, you can just pick two indices i,j if i>j and A[i] > A[j], you could say its ascending else descending.

Then, use that to define your compare function to be used in B.

int compare (const void * a, const void * b)
{
  return ( *(int*)a - *(int*)b );
}


qsort (B, sizeof(B)/sizeof(int), sizeof(int), compare);