How to sort numbers?[Homework Problem]

How do you arrange numbers according to the numbers you sort in array?
I can't really figure it out, if I don't finish this then I will fail ;__;

like this
subject1: 90
subject2: 80
subject3: 100
into this
subject3: 100
subject1: 90
subject2: 80

my codes(we are using Turbo C++):

#include<iostream.h>
#include<conio.h>
#define max 100
main()
{
clrscr();
float average, b, c, d, e, total=0, grade[max];
char name[50];
cout<<"\nEnter your name: ";
cin>>name;
cout<<"\nEnter number of subjects: ";
cin>>c;
for(b=1;b<c+1;b++)
{
cout<<"\nSubject"<<b<<": ";
cin>>grade[b];
total=total+grade[b];
}
for(b=1;b<=c;b++)
for(d=b;d<=c;d++)
if(grade[b]<grade[d])
{
e=grade[b];
grade[b]=grade[d];
grade[d]=e;
}
cout<<"\nSorted Grades: ";
for(b=1;b<c+1;b++)
{
cout<<"\nSubject"<<b<<": "<<grade[b];
}
average=total/c;
cout<<"\n"<<name<<", you have "<<c<<" subjects,";
cout<<"\nYour average is "<<average;
cout<<"\nRemarks: ";
if ((average>=70)&&(average<=100))
{
cout<<"Passed";
}
else if ((average>=66)&&(average<=69))
{
cout<<"Remedial";
}
else if ((average>=51)&&(average<=65))
{
cout<<"Failed";
}
else
{
cout<<"Invalid";
}
getch();
return 0;
}

pls. send me the codes >__<
Have you covered a 'struct' or 'class' keyword so you can associate the grade and subject together?
I think the following code is where the mistake happens:

for (b=1;b<=c;b++) {
for (d=b;d<=c;d++) {
if (grade[b]<grade[d]) {
e = grade[b];
grade[b] = grade[d];
grade[d] = e;
}
}
}

If you change the second for-loop from: for (d=b;d<=c;d++)

to: for (d=1;d<=c;d++) it should work.

The problem with d=b is the following:

Consider the array holds the numbers: 5 1 2 3 4

Watch what happens with the number 4:

In the first iteration of the outer loop it sorts to: 5 2 3 4 1

In the second iteration of the outer loop it sorts to: 5 3 4 2 1

Now the third iteration follows and d is set to 3. And that is the problem, it starts with 4, compares 4 to 2 and doesn't make the comparison 3 < 4. If d is set to 1 the sorting starts with the first element all through the array every time. It is a bit inefficient but it should work.

I hope that helps.
Last edited on
Topic archived. No new replies allowed.