I have this function:
int sort(book *data, int books, char mode, char sortBy) {
int i, j;
book aux;
aux.cat = malloc(sizeof *(aux.cat));
if(sortBy == 'n') {
for(i = 0; i < books; i++) {
for(j = i; j < books; j++) {
if(mode == 'a') {
if(strcmp((data + i)->fname, (data + j)->fname) > 0) {
aux = *(data + i);
*(data + i) = *(data + j);
*(data + j) = aux;
}
}
else {
if(strcmp((data + i)->fname, (data + j)->fname) < 0) {
aux = *(data + i);
*(data + i) = *(data + j);
*(data + j) = aux;
}
}
}
}
}
else {
for(i = 0; i < books; i++) {
for(j = i; j < books; j++) {
if(mode == 'a') {
if(strcmp((data + i)->categ, "Fictiune") == 0) {
if(((data + i)->cat)->price > ((data + j)->cat)->price) {
aux = *(data + i);
*(data + i) = *(data + j);
*(data + j) = aux;
}
}
}
else {
if(strcmp((data + i)->categ, "Fictiune") == 0) {
if(((data + i)->cat)->price < ((data + j)->cat)->price) {
aux = *(data + i);
*(data + i) = *(data + j);
*(data + j) = aux;
}
}
}
}
}
}
free(aux.cat);
return 0;
}
I need to sort the data
array in two modes: ascending and descending, and by two criteria: name and price.
The question is: is there a way to write another, more compact function that will do the same thing?
And, what do you think about line 5 (aux.cat = malloc(sizeof *(aux.cat));
)? Is it a right way to initialize the cat
pointer?
These are the structures:
typedef struct {
int price, edition;
char favCharacter[SMAX];
} category;
typedef struct {
char title[SMAX], fname[SMAX], lname[SMAX], categ[SMAX];
category *cat;
} book;