我正在尝试对数组进行排序A
其元素是索引。索引引用另一个数组B
其值将决定顺序A
。所以,我想排序A
这样B[ A[i] ]
在增加。
例如:
A = [0, 1, 4, 5, 7]
B = [5, 3, 8, 2, 2, 7, 1, 6, 3, 9]
Sorted A
将会
A' = [ 7, 4, 1, 0, 5 ]
这可以通过 C 的内置排序实现吗?还是我必须编写自己的实现?
编辑:这些数组是局部函数变量。
如果你想使用qsort
,最好的做法是将 A 中的索引和 B 中的值重新包装到一个结构中,然后基于该结构的新数组创建一个比较器。例如:
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
无需使用自定义排序功能。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)