2011-04-29 93 views
0

我在排序下列數組時遇到問題。用兩個結構變量對結構數組進行排序?

如何根據temp_var[].trade_datetemp_var[].trans_amount排序temp_var[]陣列?

typedef struct  
{ 
    char trans_d     [2],  
      trans_amount   [10], 
      trans_me     [8], 
      account     [10], 
      trans     [16], 
      trade_date    [12], 
      setnt_date    [12]; 
} what_if; 

what_if temp_var[100]; 

void swap(what_if *a, what_if *b) 
{ 
    tmp = *a; 
    *a = *b; 
    *b = tmp; 
} 


void bubbleSort(what_if a[], int size) 
{ 
    for (i=0; i<size-1; i++) 
    { 
     for (j=size-1; j>i; j--) 
      if (strcmp(a[j].trade_date , a[j-1].trade_date) < 0) 
       swap(&a[j], &a[j-1]); 
    } 
} 

int main() 
{ 
    //after read the structure values 
    bubbleSort(temp_var,t_count); 
} 
+0

你的問題是什麼?您提供的代碼是否沒有編譯或運行時錯誤? – Puddingfox 2011-04-29 04:40:45

+1

這是一個功課嗎?如果是這樣,你應該指出它。 – joce 2011-04-29 04:44:40

+0

嗨puddingfox,它得到了trade_date排序,是否有任何錯誤你覺得有。(日期如20100608) – jcrshankar 2011-04-29 05:06:15

回答

0

你只要檢查第二個排序標準,如果第一個相等。請檢查trans_amount字段是否可以這樣比較。代碼可能更短,我的意圖是演示這是如何工作的。

int first = strcmp(a[j].trade_date , a[j-1].trade_date); 
if (first == 0) { 
    if (strcmp(a[j].trans_amount , a[j-1].trans_amount) < 0) 
     swap(&a[j], &a[j-1]); 
} 
else if (first < 0) { 
    swap(&a[j], &a[j-1]); 
}