c - Sort an array in place according to a sort order defined in another array -
i have array defines sort order array. example, sort array consisting of char * data[] = {"c", "b", "a"};
, sort_order
array {2, 1, 0}
- when array sorted, first element should "c"
(which data[sort_order[0]]
).
(the background have 2 arrays want sort, second array should use same sort order first one. sort {0, 1, 2}
using values first array, , i'd use sort order sort actual values of both arrays.)
the obvious solution create copy of array (new_data
), , assign every element correct value defined sort order:
for (int = 0; < n; ++i) { new_data[i] = data[sort_order[i]]; }
however, requires making copy of array. there way can swap elements of original array sort them in place without having copy array?
edit: "possible duplicate" use array, precisely trying avoid.
reorder in place, sorts both a[] , i[], rotating "cycles". each store places value in it's proper location, time complexity o(n).
// reorder in place according sorted indices in // ta temp value for(i = 0; < n; i++){ if(i != i[i]){ ta = a[i]; k = i; while(i != (j = i[k])){ a[k] = a[j]; i[k] = k; k = j; } a[k] = ta; i[k] = k; } }
i noticed you're using c. in c++, can use lambda compare function compare members of a[], based on indices in i[]. c, can use array of pointers p[] instead of array of indices i[].
/* create array of pointers a[] */ for(i = 0; < n; i++) p[i] = &a[i]; /* sort array of pointers, compare custom compare function */ qsort(p, n, sizeof(p[0]), compare); /* reorder a[] according array of pointers */ for(i = 0; < n; i++){ if(i != p[i]-a){ ta = a[i]; k = i; while(i != (j = p[k]-a)){ a[k] = a[j]; p[k] = &a[k]; k = j; } a[k] = ta; p[k] = &a[k]; } }
example custom compare qsort() if a[] contains integers. since qsort() passes pointers p[] parameters compare(), , since p[] array of pointers, passed parameters compare() pointers pointers.
int compare(const void *pp0, const void *pp1) { return( (**(int **)pp0) - (**(int **)pp1) ); }
if goal sort second array b[], based on sorting a[], add lines like:
/* ... after ta = a[i] */ tb = b[i]; /* ... after a[k] = a[j] */ b[k] = b[j]; /* ... after a[k] = ta */ b[k] = tb;
Comments
Post a Comment