1

I am Solving this problem in which I am supposed to find line segments containing points more than three from a given plane of points. I am using a comparator to sort the points considering a point as a reference and sorting other according to the slope with reference, and i am having problems with large Inputs. I am getting am an error saying "Comparison method violates its general contract!".

I have tried modifying the comparator, but It seems to work for small inputs.

`public Comparator<Point> slopeOrder() {
        return new Comparator<Point>() {
            @Override
            public int compare(Point p1, Point p2) {
                double slope1 = slopeTo(p1);
                double slope2 = slopeTo(p2);
                return slope1 == slope2 ? 0 : (slope1 > slope2 ? 1 : -1);
            }
        };
    }`

This code written in Point class, My code should output the Line segments, but The error in sorting I get is,

Exception in thread "main" java.lang.IllegalArgumentException: Comparison method violates its general contract!
    at java.base/java.util.TimSort.mergeHi(TimSort.java:899)
    at java.base/java.util.TimSort.mergeAt(TimSort.java:516)
    at java.base/java.util.TimSort.mergeCollapse(TimSort.java:441)
    at java.base/java.util.TimSort.sort(TimSort.java:245)
    at java.base/java.util.Arrays.sort(Arrays.java:1440)
    at FastCollinearPoints.<init>(FastCollinearPoints.java:28)
    at FastCollinearPoints.main(FastCollinearPoints.java:87)
  • Do any of your computed slope values happen to be "NaN"? – MFisherKDX Mar 30 '19 at 19:51
  • 1
    What does `slopeTo(p1)` do? Does it always return the same value for any given `p1`? – MFisherKDX Mar 30 '19 at 19:55
  • 1
    Related: https://stackoverflow.com/questions/8327514/comparison-method-violates-its-general-contract – Glains Mar 30 '19 at 19:56
  • Lets say that you have 3 elements you want to sort, a,b,c and your comparator determined that ac. That would be unexpected result meaning that some assumption of valid comparator was not met. So to tell you which assumption was it we would need to know more about your code, preferably in form of [mcve] (code and used input which we could use to actually reproduce your problem). – Pshemo Mar 30 '19 at 19:56
  • What do you mean with "large" values? Note also that using floats comes with rounding errors, which might be relevant here depending on how the slope is calculated. – Mick Mnemonic Mar 30 '19 at 19:59
  • Why not `return Double.compare(slope1, slope2);` – MFisherKDX Mar 30 '19 at 20:00
  • @Pshemo and MFisherKDX Thank you for your support now my code Works. – Vishesh Tayal Mar 30 '19 at 20:51
  • I'm curious what the problem was. Can you tell us? – MFisherKDX Mar 30 '19 at 22:43
  • It is as @Pshemo has written – Vishesh Tayal Apr 01 '19 at 02:54

0 Answers0