简体   繁体   中英

Can't sort this program using 'Bubble Sort' correctly

I am trying to sort this program according to the "GPA" which I would give as an input, then print this Result Sheet in a 'Descending Order', so that the student with the highest 'GPA' would be at the top in '1.' position, then the student with the second highest 'GPA' would be at the second position in '2.' like this & that's how the student with lowest 'GPA' would come last in the list. I have tried a lot but I couldn't sort this properly. What am I doing wrong here????

#include<stdio.h>
typedef struct
{
   int roll;
   char name[30];
   float gpa;
} student;
int main ()
{
   int i,n;
   scanf("%d",&n);
   student s[n];
   for (i=0; i<n; i++)
   scanf("%d%s%f",&s[i].roll,s[i].name,&s[i].gpa);
   for (i=0; i<n; i++)
   printf("Roll=%d Name=%s GPA=%.2f\n",s[i].roll,s[i].name,s[i].gpa);
   int a[n],j,temp;
   for (i=0; i<n-1; i++)
    {
        for (j=0;j<n-i;j++)
         {
             if(a[i]<a[j])
               {
                  temp=a[i];
                  a[i]=a[j];
                  a[j]=temp;
               }
         }
     }
     printf("Position by Result: ");
     for (i=0; i<n-1; i++)
       {
          printf("%.2f\n",s[i].gpa);
       }
     return 0;
    }

This should be your required solution

#include<stdio.h>
typedef struct
{
   int roll;
   char name[30];
   float gpa;
} student;
int main ()
{
   int i,j,n;
   scanf("%d",&n);
   student s[n],temp;
   for (i=0; i<n; i++)
   scanf("%d%s%f",&s[i].roll,s[i].name,&s[i].gpa);
   for (i=0; i<n; i++)
   printf("Roll=%d Name=%s GPA=%.2f\n",s[i].roll,s[i].name,s[i].gpa);
   for (i=0; i<n; i++)
    {
        for (j=i;j<n;j++)
         {
             if(s[i].gpa<s[j].gpa)
               {
                  temp=s[i];
                  s[i]=s[j];
                  s[j]=temp;
               }
         }
     }
     printf("Position by Result: \n");
     for (i=0; i<n; i++)
       {
          printf("%.2f\n",s[i].gpa);
       }
     return 0;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM