# 根据在位的另一个数组对一个数组进行排序 [英] Sorting one array based on another in place

### 问题描述

``````A = {1, 5, 4, 3, 6, 2};
B = {1, 2, 3, 4, 5, 6};
``````

``````A = {1, 2, 3, 4, 5, 6};
B = {1, 6, 4, 3, 2, 5};
``````

``````A = vector<double>(1e6);  // some random numbers
B = vector<double>(1e6);  // some random numbers
Comp comp(&A,&B);
Swap swap(&A,&B);
costume_sort(A,B,comp,swap);   // some sort function that can take costume swap and compare

class Comp {
vector<double> *A;
vector<double> *B;
Comp(vector<double> *A, vector<double> *B) : A(A),B(B) {};

bool compareTo(size_t i, size_t j) { return A->at(i) < A->at(j); };
};

class Swap {
vector<double> *A;
vector<double> *B;
Swap(vector<double> *A, vector<double> *B) : A(A),B(B) {};

void swapFnc(size_t i, size_t j) { swap(A->at(i), A->at(j));swap(B->at(i), B->at(j)); };
};
``````

STL或其他库中有没有可以做到这一点的函数？这是我在这里试图解释的想法的一种伪代码。显然，这并不准确，但我希望它清楚我的意思。

### 推荐答案

``````bool compare(const int *p0, const int *p1)
{
return *p0 < *p1;
}

int main()
{
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[]
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];
}
}
for(i = 0; i < sizeof(a)/sizeof(a[0]); i++)
std::cout << a[i] << ' ';
std::cout << std::endl;
for(i = 0; i < sizeof(b)/sizeof(b[0]); i++)
std::cout << b[i] << ' ';
std::cout << std::endl;
return 0;
}
``````