Implementation of Quick Sort for ArrayList of Object using Comparator

I have a class of Student

public Student(int ID, String firstName, String lastName, int mark) {
        this.ID = ID;
        this.firstName = firstName;
        this.lastName = lastName;
        this.mark = mark;
    }

I created an ArrayList of Student, I will need to sort them in ascending order with multiple properties with Comparator.

 public static Comparator<Student> StuNameComparator = new Comparator<Student>() {

    public int compare(Student s1, Student s2) {
       String StudentName1 = s1.getFirstName().toUpperCase();
       String StudentName2 = s2.getFirstName().toUpperCase();
       return StudentName1.compareTo(StudentName2);
    }
};



 public static Comparator<Student> StudentID = new Comparator<Student>() {

    public int compare(Student s1, Student s2) {

       int id1 = s1.getID();
       int id2 = s2.getID();
       return id1-id2;
   }};

I know, I can easily use

Collections.sort(arraylist, Student.StuNameComparator);

But here is the catch, I need to sort using Quicksort, for collection, the sort that is used is MergeSort. I know MergeSort is better, since it is stable and doesn't have n^2 as worst case, but I required to implement Quick sort

This is the first draft for quicksort, I need to change the type of the arguments But how can sort them using quicksort, by ID when needed and by firstName when needed?

    int middle = (int) Math.ceil((double)input.size() / 2);
    int pivot = input.get(middle);

    for (int i = 0; i < input.size(); i++) {
        if(input.get(i) <= pivot){
        ///somecode
    }

Answers


You need to add a comparator in your arguments and change to a list of students: public List<Student> quicksort(List<Student> input, Comparator<Student> comparator) then change your if(input.get(i) <= pivot){ to if(comparator.compare(input.get(i),pivot) <= 0){

Of course, pivot is now Student pivot = input.get(middle); and less and greater are List<student>. You just need to pass the comparator you want to the method now.


You're almost there. The only thing you need to replace is the usage of the <= operator (which only works since an Integer can be outboxed to an int with the usage of the Comparable interface:

if (input.get(i).compareTo(pivot) <= 0) {

Need Your Help

X-Frame-Options header and Google Analytics “In-page analytics”

javascript iframe google-analytics

At present we cannot use Google Analytics "In-page analytics" (it uses an iframe). This is due to the fact that we have set the X-Frame-Options header within our application to “same-origin”, is th...

Inserting HTML with my current set up - textNode

javascript jquery html textnode

Making a text editor that allows you to upload an image, and then it adds the image url and img tag to the content editable div.