是否可以在不使用比较器的情况下比较对象?

xpszyzbs  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(433)

有没有一种方法可以对数组中的元素进行快速排序 ArrayList 同时改变 ArrayList 基于排序的数组而不使用 Comparator<> 功能?

public ArrayList<PatientArray> ageSorter(ArrayList<PatientArray> pa) {
        if (pa.size() <= 1) {
            return pa;
        }

        ArrayList<PatientArray> sorted;
        ArrayList<PatientArray> smaller = new ArrayList<PatientArray>();
        ArrayList<PatientArray> greater = new ArrayList<PatientArray>();

        PatientArray middle = pa.get(0);
        int i;
        PatientArray j;
        for (i = 1; i < pa.size(); i++) {
            j = pa.get(i);

            if ((new SortAge().compare(j, middle)) < 0) { // this object comparator
                smaller.add(j);
            } else {
                greater.add(j);
            }
        }
        smaller = ageSorter(smaller);
        greater = ageSorter(greater);
        smaller.add(middle);
        smaller.addAll(greater);
        sorted = smaller;

        return sorted;
    }

    class SortAge implements Comparator <PatientArray>{
    public int compare(PatientArray a1, PatientArray a2){
        return a1.age-a2.age;
    }
n8ghc7c1

n8ghc7c11#

你可以用 sort java8上引入的list类上的方法。所以你的方法如下:

public List<PatientArray> ageSorter(ArrayList<PatientArray> pa) {
   pa.sort(Comparator.comparingInt(a -> a.age));
   return pa;
}
ev7lccsx

ev7lccsx2#

避免使用 Comparator 直接在快速排序代码中执行比较:

if (pa.get(i).age < middle.age)

虽然您没有要求提供一般性的评论,但我要注意的是,您的代码中有许多不必要的命令。

public ArrayList<PatientArray> ageSorter(ArrayList<PatientArray> pa) {
    if (pa.size() <= 1) {
        return pa;
    }

    ArrayList<PatientArray> smaller = new ArrayList<PatientArray>();
    ArrayList<PatientArray> greater = new ArrayList<PatientArray>();

    PatientArray pivot = pa.get(0);
    for (int i = 1; i < pa.size(); i++) {
        if (pa.get(i).age < pivot.age) {
            smaller.add(j);
        } else {
            greater.add(j);
        }
    }
    smaller = ageSorter(smaller);
    greater = ageSorter(greater);
    smaller.add(middle);
    smaller.addAll(greater);
    return smaller;
}

另请注意,通常会实现快速排序,以便在不创建新数组的情况下就地完成排序。
正如@holger在下面的评论中指出的,支点(作为第一个元素)的选择也很差。这里解释了原因和备选方案
虽然从技术上讲,你的算法是快速排序,但可能并不快。

相关问题