简体   繁体   中英

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
    }

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) {

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.

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