Attempt at bubble sorting

trying to sort through an array and find the largest stored value.
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
void findHighestGrade(Student students[], int n){

    bool issorted=false;

    double highestGrade;
    string highestGradeFName;
    string highestGradeLName;

    for(int i=0;i<n-1&&!issorted;i++){
        issorted=true;

        highestGrade=students[i].grade;
        highestGradeFName=students[i].firstName;
        highestGradeLName=students[i].lastName;

        for(int j=0;j<n-i-1;j++){
            if(highestGrade<students[j++].grade){
                swap(highestGrade,students[j++].grade);
                swap(highestGradeFName,students[j++].firstName);
                swap(highestGradeLName,students[j++].lastName);
                issorted=false;
            }
        }

    }
cout << highestGradeFName << " " << highestGradeLName << " " << highestGrade;
}
sorting is not a good way to find the largest or smallest value.
generally you would set (small or large) to the first value in the array, then iterate over the array once and check each number, if it is a better answer than current, you use that value, and by the end of the array, you have the answer (you may also keep the index of smallest/largest value so you can find it again, if that is useful).

that said, if you do need to sort the list for some reason,

for(int i=0;i<n-1&&!issorted;i++){
issorted=true;

this is breaking your outer loop.
You do not even need this condition and variable, just run the sort without them. If you need to know if you already sorted the list, you can track that elsewhere, but it does not belong in the sort routine. If you want to keep it and fix it, you need to set is-sorted to true only after the list is actually sorted, which either requires an iterative test (to see if it is sorted, check that every value is > previous starting at [1]) or some other approach to ensure correctness of this value.


Last edited on
How many times do you increment j between lines 17 and 20?
Topic archived. No new replies allowed.