简体   繁体   中英

How to bubble sort with structs

I tried to sort the struct/class via bubble sort method, where i want to save

I defined the struct/class like this:

public static class Student {
        String name;
        double grade;
    }

And after i insert all the data in the struct or class, i want to sort it via bubble method the entire array like this:

public static void ordenar_burbuja(Student array[]) {
    for (int i = 1; i < array.length; i++) {
        for (int j = 0; j < array.length-1; j++) {
            if(array[j].grade>array[j+1].grade) {
                Student aux = array[j];
                array[j] = array[j+1];
                array[j+1] = array[j];
            }
        }
    }
}

The idea is to sort it from the highest grade to the lowest grade, in which i create this aux variable. Which i need to change the Student name and the Student grade position. But i have problems when defining the aux variable type. Should i change the.name and.age inside the bubble sort, or is this correct?

In the last statement in the if block, change it to:

array[j+1] = aux

In the second statement, you assign array[j] to array[j+1]. Then you assign array[j+1] to array[j], which now holds a reference to the object referenced by aux. Therefore, you've just set both array[j+1] and array[j] to aux (the Student originally at array[j]), which is not what you intended to do.

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