2011-04-12 121 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++; 
    } 
} 

與第二解決方案的問題是,如果你有兩個「星期」同樣的距離,這將失敗,因爲值保存到同一個地圖索引。