I was trying to solve a problem in a online judge system: https://acm.cs.nthu.edu.tw/problem/11519/ It takes an integer n, followed with n lines of name and grade. the problem is to sort them out by grades using a stable sort algorithm. I use qsort() and giving the person's order in the compar() to stabilize the qsort(). Here is my code:
class People{
public:
char name[11];
int grade;
int order;
void print(){ printf("%s %d\n", name, grade); }
};
int compar(const void *a, const void *b){
People *A = (People*)a;
People *B = (People*)b;
if(A->grade > B->grade) return 1;
else if(A->grade < B->grade) return -1;
else if(A->order > B->order) return 1;
else if(A->order < B->order) return -1;
}
int main(){
int n;
scanf("%d", &n);
People *p = new People[n];
for(int i=0;i<n;i++){
scanf("%s %d", p[i].name, &p[i].grade);
p[i].order = i;
}
qsort(p, n, sizeof(People), compar);
for(int i=0;i<n;i++){
p[i].print();
}
}
in all of my test cases, it works without any problem, but the online judge keeps giving my submits four WAs(wrong answer). Can someone give me some clues about this? Many thanks!