2011-04-12 122 views
1

我想对多个数组并行排序。我通过qsort对一个数组排序,然后返回一个int数组,它指定了它们原始位置的索引。现在用这个int数组,我需要对其他数组进行排序。根据C中的索引数组对数组排序C

阵列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 

非常感谢

+3

向我们展示您迄今为止编写的代码。 – NPE 2011-04-12 09:11:38

+0

告诉我们你什么时候做家庭作业,并告诉我们你的尝试。你的问题的答案非常简单,你不会通过提交给你的任何进展。 – 2011-04-12 09:27:07

回答

2
for (i=0; i < 6; ++i) 
    SortedArray[IndexArray[i]] = AnotherArray[i]; 
1

这个代码在这里显示了这样做的方法有两种:

的第一种方法确实使用的qsort()。在纯C,但消耗多一点记忆它

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++; 
    } 
} 

与第二解决方案的问题是,如果你有两个“星期”同样的距离,这将失败,因为值保存到同一个地图索引。