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**,name and price.
The question is: is there a way to write another, more compact function that will do the same thing?