3 ms·
No, the compare function needs to be able to indicate when two values are equal, not just when one is smaller/larger than the other. Otherwise your sort functio
by Ajedi32 8y ago
No, the compare function needs to be able to indicate when two values are equal, not just when one is smaller/larger than the other. Otherwise your sort function will return inconsistent results for compare(a, b) and compare(b, a) when both values are equal.
- kristianp 8y agoSo someList.sort((a,b) => a => b) Would be better, because it produces a stable sort? `a - b` produces the same results, so equally valid?
- Ajedi32 8y agoNo. `(a,b) => a => b` cannot produce a stable sort in all scenarios. Would theoretically work fine for integers since there's no difference between any two instances of the same number, but consider: let arr = [ {number: 2, name: 'a'}, {number: 1, name: 'b'}, {number: 1, name: 'c'}, ] Now assume we want to sort arr with a compare function, and our sort function expects the compare function to return a boolean, not an integer. let compare = (a,b) => a.number => b.number compare(arr[0], arr[1]) //=> true, so the object named 'a' comes after 'b' compare(arr[1], arr[2]) //=> true, so the object named 'b' comes after 'c'? See the problem?
- jwilk 8y ago(I'm assuming you meant "a >= b", not "a => b".) That's still not a consistent comparison function, so the results are implementation-defined. To be consistent, it's required, among others, that if cmp(a, b) == 0 then cmp(b, a) == 0. For "a >= b", this is not always true, e.g.: » cmp(0, 1) == 0 true » cmp(1, 0) == 0 false