I am trying to sort the array of structure which takes 20 inputs and sort them using C's standard library function qsort() but not getting proper sorted output.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma pack(1)
struct player{
char name[4];
short age;
short match;
float average;
};
#pragma pack()
int comp(const void *p,const void *q){
float *a=(float*)p;
float *b=(float*)q;
if(*b-*a>0)return 1;
if(*b-*a<0)return 1;
if(*b-*a==0)return 0;
}
int main(){
struct player list[20];
for(int i=0;i<20;i++){
scanf("%s",list[i].name);
scanf("%hu %hu %f",&list[i].age,&list[i].match,&list[i].average);
}
qsort((void*)list,20,sizeof(struct player),comp);
for(int i=0;i<20;i++){
printf("%2.2f %10s %4hu %4hu\n",list[i].average,list[i].name,list[i].age,list[i].match);
}
return 0;
}
one may use the following test case to check there output.
aaa 21 22 34
qsd 33 21 44
qqq 1 2 55.2
www 33 22 12.2
ewe 22 11 13.3
qaz 22 33 12.33
aaa 21 22 34
qsd 33 21 44
qqq 1 2 54.2
www 33 22 12.2
eee 22 11 16.3
qaz 22 33 18.33
aaa 21 22 34
qsd 33 21 49
qqq 1 2 52.2
www 33 22 12.2
eee 22 11 10.3
qaz 22 33 11.33
eee 22 11 14.3
qaz 22 33 11.33