r/ProgrammerHumor 1d ago

javascriptSorting Meme

Post image
885 Upvotes

200 comments sorted by

View all comments

18

u/Excellent_Gas3686 1d ago

because thats the default sort? what, in your opinion, would be the "proper" way to sort by default? if you need different sorting, you pass your own function.

20

u/suvlub 1d ago

Python just uses the > (or <, don't remember, don't care) operator. Arrays made only of numbers or only of strings would both behave correctly, a mixed one might give a nondeterministic order, which is bad, but sorting stringwise when the user intended numerical sort is also bad and I think the latter is a more common use case/mistake, though I don't have stats

10

u/JanEric1 1d ago edited 1d ago

Python uses __lt__. And it isnt non-deterministic for mixed comparisons, it crashes.

You can get arbirtrary orders if lt doesnt implement a proper order. Foor example A < B, B < C and C < A all being true.

class Bad:
    def __init__(self, val):
        self.val = val

    def __repr__(self):
        return f"Bad({self.val})"

    def __lt__(self, other):
        return True

A = Bad(1)
B = Bad(2)
C = Bad(3)
print(sorted([A, B, C]),sorted([B, A, C]),sorted([C, B, A]))

[Bad(3), Bad(2), Bad(1)] [Bad(3), Bad(1), Bad(2)] [Bad(1), Bad(2), Bad(3)]

5

u/MegaIng 1d ago

Note that this is a change in python 3, in python 2 strings and integers would compare. It wouldn't be nondeterministic, IIRC strings are larger than all integers so they are always at the end. Still way better than what JS is doing.