簡體   English   中英

Java 快速排序 - 是否可以在不使用比較器的情況下比較對象?

[英]Java quicksort - is it possible to compare objects without using a comparator?

有沒有辦法快速排序ArrayList中的數組元素,同時根據不使用Comparator<> ZC1C425268E68385D1AB5074C17A94F 排序的數組更改ArrayList的順序?

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

避免使用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;
}

另請注意,通常會實施快速排序,以便就地完成排序 - 即無需創建新的 arrays。

正如@Holger 在下面的評論中指出的那樣,pivot(作為第一個元素)的選擇也很差。 這里解釋了原因和替代方案

雖然從技術上講,您的算法是快速排序的,但它可能並不快。

您可以使用Java 8上介紹的列表class 上的sort方法。 所以你的方法如下:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM