0

Can anyone tell what is the difference between these lines?

Arrays.sort(pairs, (a, b) -> a[0] - b[0])
Arrays.sort(pairs, (a, b) -> a[1] - b[1]);
2
  • 1
    First line will not compile because of lack of ; at the end. But if we add that ; it will try to sort arrays based on values of their first column (accessed via [0]). Second will try to sort based on values of second column (accessed via [1]). Commented Aug 15, 2021 at 8:44
  • Also, comparing the values using subtraction may fail if an integer overflow/underflow occurs, so it's better to use Integer::compare Commented Aug 15, 2021 at 12:37

2 Answers 2

1

The first sorts based on the first element of the arrays that are being sorted, and the other sorts based on the next element.

If the input was:

[2, 33], [4, 22], [3, 11]

The first would produce

[2, 33], [3, 11], [4, 22]

and the second would produce

[3, 11], [4, 22], [2, 33]
Sign up to request clarification or add additional context in comments.

Comments

0

According to your code. It looks that the first line will not execute. Because it is missing the terminator.

Arrays.sort(pairs, (a, b) -> a[0] - b[0]);

And the second line will run and it gives the output according to your input.

Arrays.sort(pairs, (a, b) -> a[1] - b[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.