我正在尝试对元素为索引的数组 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中的值重新包装成一个结构,然后根据a做一个比较器该结构的新数组。例如:
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);
}
现在您可以在结构数组上运行 qsort
,然后您可以从那里提取原始数组 A
所需的正确排序序列,而无需使用自定义排序功能。
关于c - 根据另一个数组的内容对 C 数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6076720/