はO(n^2)ソートとコンパレータを用いて、以下の一般的なJavaメソッドを実装し:Oを使用して、一般的なJavaメソッドを実装(N^2)のソートと比較
public static <E> void aSort(E[] list, Comparator<? super E> comparator)
上記の問題3で作成したクラス型の少なくとも5つの要素のリストを作成し、上記のメソッドを呼び出してリストをソートし、ソートされたリストをtoStringの呼び出しを介して出力する書き込みテストプログラム。
Unsorted:
A Circle with the radius of: [1]
A Circle with the radius of: [15]
A Circle with the radius of: [10]
A Circle with the radius of: [12]
A Circle with the radius of: [100]
私はそれが後方にこれを印刷していますが、昇順で並べ替えることになっている理由は分からないが
Sorted:
A Circle with the radius of: [100]
A Circle with the radius of: [12]
A Circle with the radius of: [10]
A Circle with the radius of: [15]
A Circle with the radius of: [1]
これは私がこれまで
を得たものですpublic static void main(String[] args) {
Circle c1 = new Circle();
Circle c2 = new Circle(15);
Circle c3 = new Circle(10);
Circle c4 = new Circle(12);
Circle c5 = new Circle(100);
Circle w[] = new Circle[5];
w[0] = c1;
w[1] = c2;
w[2] = c3;
w[3] = c4;
w[4] = c5;
CompareCircle cc = new CompareCircle();
System.out.println("Unsorted: ");
for (Circle go : w) {
System.out.println(go.toString());
}
bubbleSort(w, new CompareCircle());
System.out.println();
System.out.println("Sorted: ");
for (int i = 0; i < w.length; i++) {
System.out.println(w[i].toString());
}
public static <E> void bubbleSort(E[] list, Comparator<? super E> comparator) {
boolean needNextPass = true;
for (int k = 1; k < list.length && needNextPass; k++) {
// Array may be sorted and next pass not needed
needNextPass = false;
for (int i = 0; i < list.length - k; i++) {
if (comparator.compare(list[i], list[i + 1]) > 0) {
// Swap list[i] with list[i + 1]
E temp = list[i];
list[i] = list[i + 1];
list[i + 1] = temp;
needNextPass = true; // Next pass still needed
}
}
}
}
}
これは、これは私のCompareCircleクラス
import java.util.Comparator;
public class CompareCircle implements Comparator<Circle> {
@Override
public int compare(Circle o1, Circle o2) {
int radius1 = o1.getRadius();
int radius2 = o2.getRadius();
if (radius1 < radius2){
return radius2;
}
if (radius1 == radius2){
return radius1;
}
else
return radius1;
}
}
'bubbleSort'methodのコードですか? –
最も重要なものは含まれていませんでした。ソートの実装 – Dici
[Comparator](https://docs.oracle.com/javase/8/docs/api/index.html?java/util/Comparator.html)は次のとおりです。 (Comparator#compare'のドキュメントを参照してください)。それ以外は 'bubbleSort'が欠けているので、なぜそれが誤動作するかについてはあまり知らない。 – Paul