by Dinesh Thakur Category: Structure And Union

When structures are used to keep record of employees, students, and so on, we would need to sort them according to some criterion. For employees, it may be according to alphabetical order, designation, or pay.

Similarly, for structures of students, they may be sorted according to names in alphabetical order, or grades or marks obtained. An illustration of sorting of structures is provided by Program. The program involves data entries of structures in which the user is required to enter the name of the student and then the marks obtained in four subjects. The program totals marks and then sorts the list of students according to the total marks in descending order so that the topper is placed at top of the list. A swap function is defined in the following program for swapping of structures for sorting purposes.

# include <stdio.h>
struct Grade
  char Name[10];
  int Grade [5];
  int Total;
void swap(struct Grade *px, struct Grade *py) // Definition of Swap function
  struct Grade temp;
  temp = *px;
  *px = *py;
  *py = temp;
void main ()
  int i =0,j,k,m,a, b, c,d,count =1;
  struct Grade classX[4];
      printf("Enter Name of next student; ");
      scanf("%s", classX[i].Name);
      printf("Enter 5 grades of %s ", classX[i].Name);
      classX[i].Total = 0;
      for ( m =0; m<5;m++)
          scanf("%d", &classX[i].Grade[m]);
          classX[i].Total += classX[i].Grade [m];
         if(count>4) break;
    for(j =0; j<count-1; j++)
        printf( "\n%-15s", classX[j].Name );
        for(k=0; k<4; k++)
           printf ("%d\t", classX[j].Grade[k]);
           printf ("%d",classX[j]. Total);
    printf("\nAfter sorting the list is as below.\n");
      for(a =0; a<count-1; a++)
           for(b =0; b<count-2; b++)
         if(classX[b].Total < classX[b+1].Total)
             swap ( &classX[b], &classX[b+1]);
                   printf("\n%-15s", classX[c].Name);
                   for(d =0; d<count-1;d++)
                      printf ("%d\t", classX[c].Grade[d]);
                      printf("%d",classX[c] .Total );
                      printf ("\n");
Sorting of Structures in C

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.