基于C中的索引数组对数组进行排序
我试图并行排序许多数组。 我通过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
非常感谢
for (i=0; i < 6; ++i) SortedArray[IndexArray[i]] = AnotherArray[i];
此处的代码显示了执行此操作的两种方法:
第一种方法是在纯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
秒将距离(在我的示例中)保存到地图中,然后在地图上迭代。 一种C ++方式。
void calculate_new_order2(int week_count, float distances[], int new_order[]) { std::map ooo; for (int week=0; weeksecond; t++; } }
第二种解决方案的问题是,如果你有两个相同距离的“周”,这将失败,因为值被保存到相同的地图索引中。