2011-04-29 92 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]); 
}