Home > OS >  Can't sort this program using 'Bubble Sort' correctly
Can't sort this program using 'Bubble Sort' correctly

Time:08-01

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;
    }

CodePudding user response:

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;
    }
  • Related