可以创建第三个指针数组,a+0到a+length-1,使用只需要知道a[]中元素类型的比较,根据a[]对指针进行排序,然后根据指针数组重新排序 a[] 和 b[](在 O(n) 时间内)。
int a[8] = {7,5,0,6,4,2,3,1};
char b[8] = {'h','f','a','g','e','c','d','b'};
int *pa[8];
size_t i, j, k;
int ta;
char tb;
// create array of pointers to a[]
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++)
pa[i] = a + i;
// sort array of pointers to a[]
std::sort(pa, pa+sizeof(a)/sizeof(a[0]), compare);
// reorder a[] and b[] according to the array of pointers to a[]
// also reverts array of pointers back to a, a + size-1
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++){
if(i != pa[i]-a){
ta = a[i];
tb = b[i];
k = i;
while(i != (j = pa[k]-a)){
a[k] = a[j];
b[k] = b[j];
pa[k] = a + k;
k = j;
}
a[k] = ta;
b[k] = tb;
pa[k] = a + k;
}
}
// ...
bool compare(const int *p0, const int *p1)
{
return *p0 < *p1;
}
您还可以使用索引 0 到长度为 1 的数组,并使用 Lambda 比较根据 a[] 比较索引。此示例使用 A[]、B[] 和 I[]:
int A[8] = {7,5,0,6,4,2,3,1};
char B[8] = {'h','f','a','g','e','c','d','b'};
int I[8] = {0,1,2,3,4,5,6,7};
int tA;
char tB;
// sort array of indices to A[]
std::sort(I, I + sizeof(I)/sizeof(I[0]),
[&A](int i, int j) {return A[i] < A[j];});
// reorder A[] and B[] according to the array of indices to A[]
// also restores I[] back to 0 to size-1
for(int i = 0; i < sizeof(A)/sizeof(A[0]); i++){
if(i != I[i]){
tA = A[i];
tB = B[i];
int j;
int k = i;
while(i != (j = I[k])){
A[k] = A[j];
B[k] = B[j];
I[k] = k;
k = j;
}
A[k] = tA;
B[k] = tB;
I[k] = k;
}
}