this post was submitted on 04 Nov 2025
454 points (99.1% liked)

Programmer Humor

27193 readers
988 users here now

Welcome to Programmer Humor!

This is a place where you can post jokes, memes, humor, etc. related to programming!

For sharing awful code theres also Programming Horror.

Rules

founded 2 years ago
MODERATORS
you are viewing a single comment's thread
view the rest of the comments
[–] Buddahriffic@lemmy.world 1 points 14 hours ago

That assumes SetTimeout() is O(1), but I suspect it is O(log(n)), making the algorithm O(n*log(n)), just like any other sort.

Did some looking into the specifics of SetTimeout() and while it uses a data structure with theoretical O(1) insertion, deletion, and execution (called a time wheel if you want to look it up), the actual complexity for deletion and execution is O(n/m) (if values get well distributed across the buckets, just O(n) if not) where m is the number of buckets used. For a lot of use cases you do get an effective O(1) for each step, but I don't believe using it as a sorting engine would get the best case performance out of it. So in terms of just n (considering m is usually constant), it'll be more like O(n²).

And it's actually a bit worse than that because the algorithm isn't just O(n/m) on execution. It needs to check each element of one bucket every tick of whatever bucket resolution it is using. So it's actually non-trivially dependent on the wait time of the longest value. It's still a constant multiplier so the big O notation still says O(n) (just for the check on all ticks), but it might be one of the most misleading O(n)'s I've ever seen.

Other timer implementations can do better for execute and delete, but then you lose that O(1) insertion and end up back at O(n*log(n)), but one that scales worse than tree sort because it is literally tree sort plus waiting for timeouts.

Oh and now, reading your comment again after reading about SetTimeout(), I see I misunderstood when I first read it and thought you meant it was almost as fast as bucket sort, but see now you meant it basically is bucket sort because of that SetTimeout() implementation. Bucket sort best case is O(n), worst case is O(n²), so I guess I can still do decent analysis lol.