我正在尝试对其A元素为索引的数组进行排序.索引引用另一个数组,B其值将决定其顺序A.所以,我想对A这种情况进行排序B[ A[i] ].
例如:
A = [0, 1, 4, 5, 7] B = [5, 3, 8, 2, 2, 7, 1, 6, 3, 9]
排序A将是
A' = [ 7, 4, 1, 0, 5 ]
这可能与C的内置排序,或者我将不得不编写自己的实现?
编辑:这些数组是局部函数变量.
如果你想使用qsort,最好的办法是将A中的索引和B中的值重新包装成一个struct,然后根据一个新的struct数组创建一个比较器.例如:
typedef struct
{
int index_from_A;
int value_from_B;
} index_value_wrapper;
index_value_wrapper index_wrapper_array[5];
for (int i=0; i < 5; i++)
{
index_wrapper_array[i].index_from_A = A[i];
index_wrapper_array[i].value_from_B = B[A[i]];
}
int comparitor (const void* lhs, const void* rhs)
{
return (lhs.value_from_B - rhs.value_from_B);
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以qsort在struct数组上运行,从那里您可以提取原始数组所需的正确排序顺序,A而无需使用自定义排序功能.