I am having trouble sorting the following array.
How do I sort the temp_var[]
array based on temp_var[].trade_date
and temp_var[].trans_amount
?
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);
}
You simply check the 2nd sorting criteria if the 1st is equal. Please check wether the trans_amount field can be compared this way. The code could be shorter, my intention was to demonstrate how this works.
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]);
}
精彩评论