我试图并行排序许多数组。我通过qsort对一个数组进行排序,然后返回一个int数组,它指定了原始位置的索引。现在有了这个int数组,我需要对其他数组进行排序。
数组1:
zzz
yyy
def
abc
cde
xxx
排序后,我得到索引数组和排序数组:Idx位置数组
3 : abc
4 : cde
2 : def
5 : xxx
1 : yyy
0 : zzz
现在基于这个索引数组,我需要对另一个数组进行排序
a
b
c
d
e
f
这样就变成了
d
e
c
f
b
a
非常感谢
答案 0 :(得分:2)
for (i=0; i < 6; ++i)
SortedArray[IndexArray[i]] = AnotherArray[i];
答案 1 :(得分:1)
此处的代码显示了两种执行此操作的方法:
第一种方法是在纯C中使用qsort()..但是会消耗更多的内存
struct pair {
int distance;
int index;
};
int my_pair_compare(const void *const first, const void *const second)
{
const pair* a = (const pair*)first;
const pair* b = (const pair*)second;
if (a->distance > b->distance)
return 1;
else if (a->distance < b->distance)
return -1;
else
return 0;
}
void calculate_new_order1(int week_count, float distances[], int new_order[])
{
struct pair ab[week_count];
for (int i = 0; i<week_count; ++i) {
ab[i].distance = distances[i];
ab[i].index = i;
}
qsort(ab, week_count, sizeof(*ab), my_pair_compare);
for (int i=0; i<week_count; ++i){
new_order[i] = ab[i].index;
}
}
秒将距离(在我的示例中)保存到地图中,然后迭代地图。一种C ++方式。
void calculate_new_order2(int week_count, float distances[], int new_order[])
{
std::map<float,int> ooo;
for (int week=0; week<week_count; week++) {
ooo[distances[week]] = week;
}
int t = 0;
for (auto i=ooo.begin(); i!=ooo.end(); i++) {
new_order[t] = i->second;
t++;
}
}
第二个解决方案的问题是,如果你有两个相同距离的“周”,这将失败,因为值被保存到同一个地图索引中。