用Comparator实现对象ArrayList的快速排序

时间:2016-03-17 07:48:14

标签: java sorting arraylist

我有一班学生

 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;
   }};

我创建了一个StudentList的ArrayList,我需要使用Comparator以多个属性按升序对它们进行排序。

Collections.sort(arraylist, Student.StuNameComparator);

我知道,我可以轻松使用

    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
    }

但是这里有捕获,我需要使用Quicksort进行排序,对于集合,使用的排序是MergeSort。 我知道MergeSort更好,因为它是稳定的,并且没有n ^ 2作为最坏的情况,但我需要实现快速排序

这是quicksort的第一个草稿,我需要更改参数的类型 但是,如何在需要时使用快速排序,按ID,以及在需要时使用firstName对它们进行排序?

/* Note that using values very near 2π can be problematic. For example,
   setting `startAngle' to 0, `endAngle' to 2π, and `clockwise' to true will
   draw nothing. (It's easy to see this by considering, instead of 0 and 2π,
   the values ε and 2π - ε, where ε is very small.) Due to round-off error,
   however, it's possible that passing the value `2 * M_PI' to approximate
   2π will numerically equal to 2π + δ, for some small δ; this will cause a
   full circle to be drawn.

   If you want a full circle to be drawn clockwise, you should set
   `startAngle' to 2π, `endAngle' to 0, and `clockwise' to true. This avoids
   the instability problems discussed above. */

2 个答案:

答案 0 :(得分:0)

你几乎就在那里。您需要替换的唯一事项是使用<=运算符(仅当Integer可以通过使用int接口将Comparable发送到if (input.get(i).compareTo(pivot) <= 0) { 时才有效:

typesOfRates.myRates

答案 1 :(得分:0)

您需要在参数中添加比较器并更改为学生列表:public List<Student> quicksort(List<Student> input, Comparator<Student> comparator)然后将if(input.get(i) <= pivot){更改为if(comparator.compare(input.get(i),pivot) <= 0){

当然,数据透视表现在为Student pivot = input.get(middle);,越来越多的是List<student>。你只需要将你想要的比较器传递给方法。