0

Can some one explain me how comparator works? I mean when someone use return a-b or for example took from here (http://buttercola.blogspot.com/2015/08/leetcode-skyline-problem.html) :

 public class EdgeComparator implements Comparator<Edge> {
        @Override
        public int compare(Edge a, Edge b) {
            if (a.x != b.x) {
                return a.x - b.x;
            }

            if (a.isLeft && b.isLeft) {
                return b.height - a.height;
            }

            if (!a.isLeft && !b.isLeft) {
                return a.height - b.height;
            }

            return a.isLeft ? -1 : 1;
        }
    }

Say for example, here why they are using a.height - b.height ? or b.height - a.height ? Please explain me.

Sarah
  • 403
  • 5
  • 16
  • No one can know this. These variable names are terrible - what is `x`? What is `height`? What is `isLeft`? How are the edges being compared? What makes one edge "bigger"? The longer edge? What has `isLeft` got to do with it? – Boris the Spider Feb 20 '16 at 16:55
  • Do you understand what a `Comparator` is used for? And what the `compare()` method should return? - https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html – Codebender Feb 20 '16 at 16:56

1 Answers1

1

Using a-b is a shortcut to Integer.compare(a, b) because in the absence of overflow it returns a positive number when a > b, zero when a == b, and a negative number otherwise. b-a reverses the direction of the comparison, returning a negative when a is greater than b.

However, the subtraction approach breaks down due to overflow when the two numbers are of large magnitude, so one should use Integer.compare instead:

public class EdgeComparator implements Comparator<Edge> {
        @Override
        public int compare(Edge a, Edge b) {
            int res = Integer.compare(a.x, b.x);
            if (res != 0) {
                return res;
            }
            if (a.isLeft && b.isLeft) {
                return Integer.compare(b.height, a.height);
            }
            if (!a.isLeft && !b.isLeft) {
                return Integer.compare(a.height, b.height);
            }
            return a.isLeft ? -1 : 1;
        }
    }
    ...
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • From the link he posted, "It is guaranteed that 0 ≤ Li, Ri ≤ INT_MAX, 0 < Hi ≤ INT_MAX, and Ri - Li > 0". In that case overflows are not possible. – Jean-François Savard Feb 20 '16 at 17:05