Find the bug · #57 · Sort and search Medium Java
The biggest debt sorts last
Balances are sorted lowest first for the collections team, but the biggest debt ends up last.
On this page
The report
The collections team gets every account sorted by balance, lowest (biggest debt) first. With very large balances in the mix, the list comes out in the wrong order, and the biggest debt isn’t first.
The code
Read it first: what should it do? Then click the line where you think the bug is.
class Accounts {
// Sorts balances from lowest to highest (debts first), for the collections team.
static void sortByBalance(List<Integer> balances) {
balances.sort((a, b) -> a - b);
}
}Read it, then pick a line.
What is 1,500,000,000 − (−1,500,000,000), and does it fit in an int?
What it prints
Running it on a small example prints the output on the left. It should print the output on the right.
List<Integer> b = new ArrayList<>(List.of(1_500_000_000, -1_500_000_000, 0));
Accounts.sortByBalance(b);
System.out.println(b);It prints
[1500000000, -1500000000, 0]
It should print
[-1500000000, 0, 1500000000]
Show the answer: the bug, the fix, and how you’d find it
The bug (line 4)
Line 4 compares by subtracting: a - b. For a large positive and a large negative balance, the difference is bigger than an int can hold, overflows, and comes out with the wrong sign, so the sort thinks the debt is bigger than the credit. Use Integer::compare, which never subtracts.
The fix
1class Accounts {2 // Sorts balances from lowest to highest (debts first), for the collections team.3 static void sortByBalance(List<Integer> balances) {4 balances.sort((a, b) -> a - b);4 balances.sort(Integer::compare);5 }6}How you’d find it
- Reproduce with balances near the int limits: the order comes out wrong. Small balances sort fine.
- Right for small numbers, wrong for huge ones: overflow. Work out the comparator by hand: 1.5 billion minus −1.5 billion is 3 billion, past the int limit.
- A comparator only needs the sign right, and subtraction can’t promise that.
The test that catches it
It fails on the code above and passes once it’s fixed. Keep it, so the bug can’t come back.
List<Integer> x = new ArrayList<>(List.of(2_000_000_000, -2_000_000_000, 5));
Accounts.sortByBalance(x);
check(x.equals(List.of(-2_000_000_000, 5, 2_000_000_000)), "sorted");Where else this bites
- JavaScript’s
(a, b) => a - bis safe for normal numbers, but not for BigInt or huge values. - Comparators that aren’t consistent can even make Java’s sort throw “Comparison method violates its general contract”.