sorting problem

i want to sort the average in ascending and descending order. but only the descending was success. Help me solve it please, or any mistake that i made ?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
 #include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct students_t
{
  string name;
  int age;
  int average;
} data [5];

int main ()
{
    
    data[0].name="young jian";
    data[0].age=           17;
    data[0].average=       92;
    
    data[1].name="vijay     ";
    data[1].age=           19;
    data[1].average=       90;
    
    data[2].name="ahmad     ";
    data[2].age=           20;
    data[2].average=       89;
    
    data[3].name="jack      ";
    data[3].age=           21;
    data[3].average=       85;
    
    data[4].name="Mehran    ";
    data[4].age=           23;
    data[4].average=       98;
    
    int temp;
    
    cout<<"ascending order"<<endl;
    
    for(int i=0; i<5; i++){
        for(int j =0; j < 5 - 1-i; j++){
            if(data[j].average > data[j+1].average){
                temp = data[j].average;
                data[j].average = data[j+1].average;
                data[j+1].average = temp;
            }
        }
        cout<<data[i].name<<"\t\t";
        cout<<data[i].age<<"\t\t";
        cout<<data[i].average<<"\n";
    }
        cout<<endl<<"descending order"<<endl;
    for(int i = 4; i >= 0; i--){
        for(int j =0; j < 5 - 1 - i; j++){
            if(data[j].average > data[j+1].average){
                temp = data[j].average;
                data[j].average = data[j+1].average;
                data[j+1].average = temp;
            }
        }
        cout<<data[i].name<<"\t\t";
        cout<<data[i].age<<"\t\t";
        cout<<data[i].average<<"\n";
    }
    
  return 0;
}
It doesn't matter in what order you iterate over the elements. What matters is how you compare them.
Topic archived. No new replies allowed.