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?
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;
}
}
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 Comparator
s to sort by different fields.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With