Reputation: 3
so I put the number and alphabet into an array and a string but they are related as in 10b must be 10b and 4b must be 4b.
I am hoping to sort the string with the number alphabetically from a to b to c... etc
The number with the ASCII odd alphabet should be in ascending order but the number with the ASCII even alphabet should be in descending order.
i.e. as the following case should be 5a 12a 10b 4b 4h
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char *argv[]) {
char *alpha[] = {"b", "b", "h", "a", "a"};
int num[5]= {4,10,4,12, 5};
int i;
printf("The classes are ");
for (i=0; i<5; i++){
printf("%d%s ", num[i], alpha[i]);
}
printf("\n");
printf("The classes are rearragnged to:");
return 0;
}
Any idea on how should I sort them?
(Extra note: I tried bubble sort but doesn't really work with an array and string... I also put them both in a string as well but when sorting with 4b and 10b, it goes random as it cant compare the correct string position with a single digit with double digit...)
Upvotes: 0
Views: 130
Reputation: 35154
If you treat alpha
and num
as pairs, the best way of expressing this is usually to combine them in one object (and then to sort these objects) rather than managing two separate arrays (which do not express this "pair"-relationship). If - for some reason - you are not allowed to change the data structure, then there are other ways as well (for which you can ask later, if you like). But let me propose here the solution that expresses the "pair"-intention:
struct classStruct {
char *alpha;
int num;
};
int compareClassStructByLetter(const void *c1, const void *c2) {
struct classStruct* c1Ptr = (struct classStruct *)c1;
struct classStruct* c2Ptr = (struct classStruct *)c2;
int result = 0;
int strcmpResult = strcmp(c1Ptr->alpha, c2Ptr->alpha);
if (strcmpResult != 0) {
result = strcmpResult;
}
else {
result = c2Ptr->num - c1Ptr->num; // ascending order...
char c = *c1Ptr->alpha;
if (c % 2) { // odd alpha? (for example, 'a'== 65 == odd)?
result = -result; // reverse order to descending
}
}
return result;
}
int main(int argc, char *argv[]) {
int i;
struct classStruct classes[5] = {
{ "b", 4 },
{ "b", 10 },
{ "h", 4 },
{ "a", 12 },
{ "a", 5 }
};
printf("The classes are ");
for (i=0; i<5; i++){
printf("%d%s ", classes[i].num, classes[i].alpha);
}
printf("\n");
qsort(classes, 5, sizeof(struct classStruct), compareClassStructByLetter);
printf("The classes are rearragnged to:");
for (i=0; i<5; i++){
printf("%d%s ", classes[i].num, classes[i].alpha);
}
printf("\n");
return 0;
}
The output of this program is then:
The classes are 4b 10b 4h 12a 5a
The classes are rearragnged to:5a 12a 10b 4b 4h
Upvotes: 1