Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Sorting Objects with Multiple Parameters

I have recently been working to better my understanding of sorting algorithms and their relationship to different types of input. Currently, I'm working on a Student Management program where each student has three parameters: Last Name, GPA, and User ID (String, double, int). They are each stored in a Student class with those three parameters, and there are DOZENS of students (a key feature of the program is to input, remove, and update students).

My question is: using the major sorting algorithms (mergesort, quicksort, etc.), what is the best way to sort my list of students by each parameter? For instance, what is the best way to perform a mergesort to sort the list by GPA? Or to use quicksort to sort the list by last name?

Essentially my question boils down to...I can sort these objects if they didn't have three parameters (writing a mergesort to sort 100 numbers is very easy for me). How do I manage the other two parameters and make sure they're accessible after the sort?

like image 904
benny.bennett Avatar asked Feb 21 '23 22:02

benny.bennett


2 Answers

The way this is done in Java is to use different Comparators. Then you say:

Collections.sort(list, new NameComparator());

Or

Collections.sort(list, new GpaComparator());

These comparators use different fields to define the order between two elements.

For example, Name Comparator might be:

class NameComparator implements Comparator< Student> {
    @Override public int compare(Student left, Student right) {
        return left.getName().compareTo(right.getName());
    }
}

And GpaComparator might be

class GpaComparator implements Comparator< Student> {
    @Override public int compare(Student left, Student right) {
        if (left.getGpa() < right.getGpa()) {
            return -1;
       } else if (left.getGpa() > right.getGpa()) {
            return 1;
       } else {
           return 0;
     }
 }
like image 118
daveb Avatar answered Mar 02 '23 15:03

daveb


The typical way to do this is to write a generic sorting algorithm on any type that accepts a Comparator, and then to write different Comparators to sort by different fields.

like image 41
Louis Wasserman Avatar answered Mar 02 '23 15:03

Louis Wasserman