I have this piece of code and it doesn't work as expected. Can someone tell me why this doesn't sort triangles by area properly? I am looking at code for 1h and can't realize where is problem, when I run program it sorts some of it but few of them are still unsorted.
import java.util.Arrays;
import java.util.Comparator;
class Triangle {
public final int a;
public final int h;
public Triangle(int a, int h) {
this.a = a;
this.h = h;
}
@Override
public String toString() {
return "Triangle: a = " + a + " cm and h = " + h + " cm";
}
}
class Program {
public static void main(String[] args) {
Triangle[] triangles = new Triangle[] {
new Triangle(1, 6),
new Triangle(1, 1),
new Triangle(1, 5),
new Triangle(1, 8),
new Triangle(1, 2),
new Triangle(1, 4),
new Triangle(1, 7),
new Triangle(1, 9),
new Triangle(1, 3)
};
System.out.println("ORIGINAL:");
for (Triangle t : triangles) {
System.out.println(t);
}
Arrays.sort(triangles, new CmpByArea());
System.out.println();
System.out.println("SORTED:");
for (Triangle t : triangles) {
System.out.println(t);
}
}
}
class CmpByArea implements Comparator<Triangle> {
@Override
public int compare(Triangle t1, Triangle t2) {
double area1 = t1.a * t1.h / 2;
double area2 = t2.a * t2.h / 2;
return (int) Math.signum(area1 - area2);
}
}