2012-11-23 63 views
-2

我有一個結構數組。可以稱之爲structsarrayc中的數組排序

而且我有一個int數組,其中int是索引的指數。讓我們把它叫做indexarray

我想排序indexarray但我想比較的intstructsarray

能與設置進行任何方式的排序?

+1

http://mattgemmell.com/2008/12/08/what-have-you-tried/ –

回答

3

你有一個比較函數像這樣:

int my_compare(const void *a, const void *b) 
{ 
    int index1 = *((const int *) a); 
    int indexb = *((const int *) b); 

    return structsarray[index1].field - structsarray[index2].field; 
} 

的參數是指向要排序的數組中的值。我將常量void指針轉換爲常量int指針,然後解引用該指針以獲取實際值。

+0

但我可以以某種方式傳遞一個指向'structsarray'的指針作爲參數嗎? – nkobber

+0

@Razcou如果你將'structsarray'傳遞給'qsort',那麼比較函數會得到兩個指向結構的指針,所以你必須做'struct my_struct * struct1 =(struct my_struct *)a;' –

0

提供的信息非常有限。 可能是你可以做如下:

算法例如: 冒泡排序:

for (c = 0 ; c < (n - 1); c++) 
    { 
    for (d = 0 ; d < n - c - 1; d++) 
    { 
     if (index[d] > index[d+1]) /* For decreasing order use < */ 
     { 

     /* Sort index */ 
     swap  = index[d]; 
     index[d] = index[d+1]; 
     index[d+1] = swap; 

     /* Sort struct using above index */ 
     swap  = struct[d]; 
     struct[d] = struct[d+1]; 
     struct[d+1] = swap; 

     } 
    } 
    }