Searching for "qsort()"

Q:

How would you use qsort() function to sort an array of structures?

Answer

#include "string.h"


#include "stdlib.h"


struct stud


{


       int rollno;


       int marks;


       char name[30];


};


int sort_m (struct stud *, struct stud *);


int sort_name (struct stud *, struct stud *);


int sort_marks (struct stud *, struct stud *);


 


main()


{


static struct stud ss[] = {


                                            { 15, 96, "Akshay" },


                                            { 2, 97, "Madhuri" },


                                            { 8, 85, "Aishvarya" },


                                            { 10, 80, "Sushmita" }


                                   };


int x,w;


clrscr();


w = sizeof (struct stud);


 


printf ('\nIn order of roll numbers:");


qsort (ss, 4, w, sort_rn);


for(x=0; x<4;x++)


     printf ("\n%d%s%d", ss[x].rollno, ss[x].name,ss[x].marks);


 


printf("\n\nIn order of names:");


qsort(ss, 4, sort_name);


 


for (x=0; x<4;x++)


      printf("\n%d%s%d",ss[x].rollno, ss[x].name,ss[x].marks);


printf("\n\nIn order of marks:");


qsort(ss,4,w,sort_marks);


 


for (x=0;x<4;x++)


      printf ("\n%d%s%d",ss[x].rollno,ss[x].name,ss[x].marks);


}


int sort_rn (struct stud *t1, struct stud *t2)


{


     return (t1->rollno-t2->rollno);


}


 


int sort_name (struct stud *t1, struct stud *t2)


{


     return (strcmp(t1->name,t2->name));


}


int sort_marks (struct stud *t1, struct stud *t2)


{


     return (t2->marks-t1->marks);


}


 


 


 

Report Error

View answer Workspace Report Error Discuss

Subject: Programming