[英]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.