12 ms·
Sleep Sort
- xorglorb 15y agoIt's actually an interesting solution. If you reduced the time waited to a microsecond, then it would take about a second to sort 1M elements. Definitely not an optimal solution, and has a bit of potential for race conditions (if one thread/process got hung up on I/O), but interesting none the less.
- dreamux 15y ago_lots_ of potential for race conditions.
- sterwill 15y agoEasy to solve, just start them in order.
- windsurfer 15y agoBut then it's already sorted...
- dkersten 15y agoO(1) sorting!
- danparsonson 15y agoDon't forget the setup time, and the need to spawn one million threads, and then have them all wait until you've spawned the last one before they start their timers.....
- forgotusername 15y agoAt that resolution a modern OS is likely to round up the delay to some energy-saving number, and the run queue is going to be so contended that even if the timers fired at the right time, there would be little guarantee the processes awoke in the desired order. I think on Linux the granularity thing is true for e.g. nanosleep(), but there is also the POSIX clock_*() functions, which I think guarantee higher resolution.
- leif 15y agohigher resolution, but I don't think precision (especially in the face of I/O)
- tomp 15y agoAs long as all the threads are running before the first one finishes... You would have to measure the speed of spawning new threads in your runtime, and adjust the linear timestep dt * x (where x is the element) for that, e.g. for 2 1 1 1 1 1 1 1 1 1 0 you would have to make the waiting time for 2 be 2 * dt + epsilon, where epsilon is a function of the elements position in the list to be sorted. Even if you did that perfectly, it is still only a probabilistic sorting algorithm, with potential for error.
- JadeNB 15y agoThe problem, I think, is that the running time of the algorithm is measured not by the number of inputs, but by the size of the largest input—so, as Estragon (http://news.ycombinator.com/item?id=2657959 http://news.ycombinator.com/item?id=2657959) (transitively) points out, there's not an appreciable difference between sorting `(1..10^3, 10^6)` and `(1, 10^6)`.
- justin_vanw 15y agoThis isn't interesting at all. every thread sleeps for that long. When you sleep, something like this happens: The OS is told to wake up your thread after x time has elapsed. It puts this request into some data structure which it does something like poll from time to time so it knows what thread to wake up at what time. You are offloading your sort to the OS, which is probably then doing something like putting it into a linked list of timeouts that have been registered (maybe a heap?). After approximately the allotted time, some mechanism akin to a signal is used to tell your thread to wake up. Also, usually the thread will just sleep AT LEAST as long as you tell it to sleep, but if the system is busy it could sleep a long time more. Threads can be woken up at the same time or slightly out of order, or 'woken up' only to find that all the cpu's are working on something else, and thus waiting for a time slice, getting one, then waiting again, and not getting to use stdout for weeks. It's uncommon to see machines with really high load these days, but a 1 core computer with 25000 processes all competing for CPU time, and which is swapping heavily, will potentially run each process millions of times slower than running one process. TLDR; This is curious, but will fail much of the time, has huge memory overhead. Lots of good sorts are in place, this one requires something like 8mb per thread on linux due to the stack allocated for the thread. At best this takes millions of years potentially, and just does some other sort anyway.
- peregrine 15y agoI think its more of a novelty then a serious sorting algorithm. Seeing as though this comes from 4chan I think the author did it purely for the 'lulz'.
- burgerbrain 15y agoYou've just done a pretty great job of convincing me the opposite of your original "isn't interesting at all" thesis.
- klochner 15y ago"But that's a tautology, of course the chicken wanted to get to the other side if it crossed the road."
- pbiggar 15y ago
- nick_urban 15y agoI don't think this is meant to be serious. Maybe on a quantum computer...
- allochthon 15y agoIt's a joke, guys.
- peterwwillis 15y agoToo bad it's not a funny one
- peregrine 15y agoI think the more interesting solutions are deeper in the thread mainly #43, #44, #83. Mostly just for fun but its neat to see an Erlang solution since this should be right up its alley.
- ctdonath 15y agoPlease share for the net-nannied among us.
- chops 15y agoErlang version for you: -module(sleepsort). -export([sort/2, spawn_waiters/3, wait/4]). sort(Xs, Conv) -> spawn(?MODULE, spawn_waiters, [Xs, Conv, self()]), receive {spawned, N} -> queue(N) end. queue(N) -> queue(N, []). queue(0, Xs) -> lists:reverse(Xs); queue(N, Xs) -> receive {item, X} -> queue(N - 1, [X|Xs]) end. spawn_waiters(Xs, Conv, P) -> spawn_waiters(P, Conv, Xs, 0). spawn_waiters(P, _, [], N) -> P ! {spawned, N}; spawn_waiters(P, Conv, [X|Xs], N) -> spawn(?MODULE, wait, [X, Conv(X), P, self()]), receive monitored -> ok end, spawn_waiters(P, Conv, Xs, N + 1). wait(X, T, Q, P) -> Ref = erlang:monitor(process, P), P ! monitored, receive {'DOWN', Ref, process, P, _} -> ok end, timer:sleep(T), Q ! {item, X}. Edit: finally got the formatting right.
- ricardobeat 15y agojavascript version for you: var numbers = process.argv.slice(2) , output = [] , negative = [] for (var i=0, ln=numbers.length; i<ln; i++){ var n = +numbers[i] setTimeout((function(n){ return function(){ if (n<0) negative.unshift(n) else output.push(n) if (output.length + negative.length === numbers.length) { return console.log(negative.concat(output)) } }})(n), Math.abs(n)/1000) } Works with negative numbers. $ node sleepsort -2 1 0.1 4 -1 7 -3 9 [ -3, -2, -1, 0.1, 1, 4, 7, 9 ]
- nlco 15y agoyour code can be simplified a bit: function sleep_sort (inputs) { function child (number) { setTimeout(function () {console.log(number)}, Math.pow(2,number)) } for (var i = 0; i < inputs.length; ++i) child(inputs[i]) } sleep_sort(process.argv.slice(2));
- kabdib 15y agoOne of my less well received interview questions is: "Okay, we both know theoretical lower limits on sorting. Can you come up with a terminating algorithm that is most /pessimal/?" Usually I get a blank stare. Sometimes I get a great answer.
- skrebbel 15y agoI think you get the blank stares because half the interviewees don't know what "pessimal" means.
- cubicle67 15y agoCmd+Ctrl+d: no entries found I guess it's a mix of optimal and pessimistic. Pessimistically optimal ("This may be optimal, but I doubt it") or Optimally pessimistic ("This is absolutely the worst possibly outcome ever") :)
- Leynos 15y agoThe latter: https://secure.wikimedia.org/wiktionary/en/wiki/pessimal https://secure.wikimedia.org/wiktionary/en/wiki/pessimal The other time I've seen a similar derivation used is in "The Story of Mel" 'Mel called the maximum time-delay locations the "most pessimum". '
- sanj 15y agoI always like the "shaking box" algorithm: 1. Check if list ordered. If it is, we're done! 2. Randomize order of list. Go back to step 1. N!
- spatulon 15y agoThis is usually known as bogosort. http://en.wikipedia.org/wiki/Bogosort http://en.wikipedia.org/wiki/Bogosort
- skimbrel 15y agoThis is more commonly known as bogosort (http://en.wikipedia.org/wiki/Bogosort http://en.wikipedia.org/wiki/Bogosort), and it's a good start for running time but isn't guaranteed to terminate. See my other comment for a link to something that goes one better than bogosort on running time.
- rajasharan 15y agomy first reaction was it's going to be O(9^n) worst case - but there is & after f "$1" which spawns its own process for each number. Not bad - maybe its a good algo if all are single digits
- srl 15y agoOf course, the proper algorithm, when all are single digits, is to use an array [10]int.
- IgorPartola 15y agoOptimize it by making the sleep time be log(x) instead of x or a fraction of x. That makes it O(log n) complexity :). Use any monotone increasing function really.
- mcantor 15y agoIt finally happened. HN cut out the middle man. Instead of linking to something on Reddit about 4chan, we finally just linked straight to 4chan.
- ulisesroche 15y agoThe sky really is falling :/ e: Dang, maybe I should have used a snark mark.
- mishmash 15y agoNice, and now the HN home page is likely three clicks away from child pornography.
- mishmash 15y agoWow 14 downvotes and counting (it's already greyed out, but thx guys! ;) for making an inconvenient but almost certainly true statement. So here's the thing: the chan culture in general can be refreshingly great and diverse in many ways. It has cool, talented, and funny people, including fellow HN members (check out the society meta-boards sometime). I've been there for years, and am even friends with someone who admins a relatively popular subchan. This is not some ignorant hate-based butthurt religious rant here - and I will gladly eat the signed integers to prove it... my problem with this submission is that part of the chan-sub-culture that 4chan represents and helped popularize, the part that resides at 4chan.org is a culture of desensitivity and inaction with regards to the posting of child porn. It's continually posted and often stays up for hours. It's been this way for years. I go back every once in a while hoping it's changed, but as of last week, it hasn't. We can argue all day about about moot's level of involvement (maybe pg has a comment regarding founders setting the expectations and social norms of a community?), moderation strategy, it's associated seemingly "positive" effects on society at large (memes, hacktivism, etc.), but those are not the issue. The issue is that by posting this to HN, we are both indirectly via the network effect, and directly via advertising revenue, supporting a community with less than ideal standards relating to the sharing of pictures of sexually abused children. And yes, ad-free text boards count too due to spillover. Next time just post the story/example or something in a Tell thread, and have the discussion here. my 0.02$ also, here's an archive img of the linked discussion for those still at work: http://i.imgur.com/LdgLc.jpg http://i.imgur.com/LdgLc.jpg
- TeMPOraL 15y agoReminds me of "ListBox sort" story I heard once; it was about a programmer who, wanting to sort strings and not knowing how to do this, put strings into a hidden ListBox GUI control and then read them back in sorted order.
- comex 15y agoWhen I was, like, 10, I wanted to find the distance between two points in a Visual Basic program but didn't know how, so I created a Line control between the points and tried to read back the Width. (It didn't work, since Width was just the thickness of the line.)
- Sukotto 15y agoWould someone please summarize the article? There's no way I'm clicking a 4chan link from here at work.
- jessedhillon 15y agoSomeone posted an "algorithm" for sorting integers in bash by calling a function f, which sleeps for n seconds and then prints n. Smaller numbers will cause f to wake up and print earlier than larger numbers, so the result is that you have a sorted list print back. Unless you have small numbers, or negative numbers, or very closely grouped numbers, or... It was a joke, I think. (I hope)
- SwellJoe 15y agoIt is currently SFW (it seems to have images disabled). But, the post that started it all is: Man, am I a genius. Check out this sorting algorithm I just invented. #!/bin/bash function f() { sleep "$1" echo "$1" } while [ -n "$1" ] do f "$1" & shift done wait example usage: ./sleepsort.bash 5 3 6 3 6 3 1 4 7
- DarkShikari 15y agoIt is currently SFW (it seems to have images disabled). /prog/ is a text-only board.
- aw3c2 15y agoThere is an ASCII swastike with racist slur in the thread now.
- pnathan 15y agoThat's actually a very clever hack. I'm not sure how I'll put it to use, but I'll definitely keep it in my mental store.
- SwellJoe 15y agoWell, I would hope you wouldn't use it to actually sort integers...but, yes, bash is surprisingly good at parallel jobs (or, at least, it is surprisingly easy to create parallel jobs in bash), and that's one way to go about it. One could bash together a cheap and cheerful queueing system with something like this...but only if order isn't all that important (race conditions are almost guaranteed), timing isn't all that important (Linux has high precision timers but bash/sleep don't use them, as far as I know; and you'd need RT patches to get near realtime performance from the kernel, anyway), and only if you know with reasonable certainty the bounds on how many things will be queued before-hand. So...probably not very useful, after all. But, a fun thought experiment, regardless. I feel awake after reading the whole thread. Honestly, I wish there were more posts like this on HN.
- SwellJoe 15y agoI was impressed by the brevity of the C solution using OpenMP (comment #81), especially compared to significantly more verbose Erlang and Haskell examples. I kept reading it, thinking, "Where's the fork?" and seeing nothing but a simple for...and then remembered that # is a preprocessor directive, rather than a comment, in C, and then googled for "parallel omp for". So, I actually learned something today from that ridiculous thread: http://en.wikipedia.org/wiki/OpenMP http://en.wikipedia.org/wiki/OpenMP Also, the Perl 6 one-liner is sort of laughably cute . I'm not sure I believe it would actually work, but if it does, the conciseness of Perl 6 is even higher than I'd realized; dropping about 9 words from the Perl 5 one-liner (which is already very small). But, I learned about the hyper operators in Perl 6, which is also cool: http://perl6advent.wordpress.com/2009/12/06/day-6-going-into-hyperspace/ http://perl6advent.wordpress.com/2009/12/06/day-6-going-into... In short, that was awesome reading over my morning tea.
- gazrogers 15y agoThere's a few short implementations of this algorithm on CodeGolf.SE: http://codegolf.stackexchange.com/questions/2722/implement-sleep-sort http://codegolf.stackexchange.com/questions/2722/implement-s...
- SwellJoe 15y agoI'm relieved to note that Haskell and Erlang don't have to be ridiculously verbose. There's even an Erlang one-liner that is competitive with the Perl and Ruby implementations for brevity. I was amused to note that Perl is still the shortest implementation, and could be shorter (though the frighteningly short Perl 6 implementation mentioned in the 4chan thread is either wrong, or the implementation of the <<. operator is still unfinished in Rakudo Star, because it does not actually do the job; I don't understand the hyperoperators well enough yet to know which is true).
- smosher 15y agoAlso, the Perl 6 one-liner is sort of laughably cute . I'm not sure I believe it would actually work I don't think any current implementation supports auto-parallelization of hyperops. Regardless, hyper is really only spec'd to remove the result-ordering requirements so that it may optimize it (I wouldn't be surprised if was executed in chunks in slightly more sophisticated implementations.)
- _delirium 15y agoInteresting idea I hadn't seen before. It's basically bucket sort, but using the scheduler to hold the bins.
- _delirium 15y agoCorrecting myself: while that's what I think of it conceptually (everything is placed into integer-valued "bins" via the integer parameter taken by sleep()), implementation-wise it's probably equivalent to heapsort or something similar, depending on whether the scheduler stores sleeping threads in a heap or some other data structure.
- sbierwagen 15y agoFor those few of you not conversant with 4chan, the dis subdomain is text only, like the original 2ch. The textboards tend to be disdainful of the imageboards, and incidentally, they get much less traffic, since it's impossible to post porn on them. The mailto:sage links in some of the posts are essentially public downvotes; from the Japanese "下げ", meaning "down", and pronounced "sah ge".
- nateberkopec 15y agoI consider myself conversant with 4chan, and I had no idea that the dis subdomain existed. I always wondered if there was a chan for hackers...now I realize there is. And oh boy, what a chan it is.
- rplacd 15y agoHave you read your SICP today? You'll fit right in if you have.
- dkersten 15y agoSo long as you're an EXPERT PROGRAMMER who despises programming SEPPLES.
- kabushikigaisha 15y agoMost decent sized chans have their /prog/ board. See shii's Overchan[1] for a comprehensive list of chans on the WWW. Shii personally runs a pretty nice chan called 4-ch[2] with a large and decent DQN[3] textboard. (S)he founded this chan after being banned from 4chan and SomethingAwful. I don't know whether shii still frequents 2ch or Futaba. I don't consider the English chans online for programming to be all that great. Most (if not all) are textboards with few postings and lots of trolling over the last 3 years. I don't know the state of the huge Japanese ones however, as I do not frequent them or read the language. [1] http://shii.org/2ch/ http://shii.org/2ch/ [2] http://4-ch.net/4ch http://4-ch.net/4ch [3] 4-ch.net/dqn/
- 15y ago
- Estragon 15y agoThat was a brilliant joke, hardest I've laughed all day. Some choice comments: I don't like to wait 218382 seconds to sort '(0 218382) If you slept exp(n) instead of n it could easily include negative integers too*!* Oh shit, we're busted, there's a REALISTICALLY THINKING PERSON in this thread!
- uniclaude 15y agoSorry, can't open the link here (blocked). May anyone please give a cached version? (or even a link to a full page screenshot, a la 4chan). - Thanks
- GBond 15y agoWow, 4chan on HN frontpage is a milestone. I recall reading somewhere 4chan (among few other sites) articles are auto-flagged when submitted.
- liedra 15y agoI used to work as an editor for freshmeat.net and we would get hilarious submissions like this quite frequently. For example, the "revolutionary new file compression algorithm" that quite literally converted a file into binary and removed all the 0s. Such a shame that the author "hadn't gotten around to" writing a de-compression tool! We were often quite sad that we couldn't publish some of these gems, they were brilliant.
- justin_vanw 15y agoAre those of you whom are saying there is anything at all good or usable about this approach just trolling? Pleaaase just be trolling, if my opinion of humanity goes any lower I'll have to start building a 'compound'.
- smosher 15y agoNote to future historians: In the age before commercialized internet access humans found humor in absurdism, irony, satire and sometimes even sarcasm. Today these forms are no longer considered humorous but malicious and offensive, and are now classified under the blanket term trolling.
- ltbarcly3 15y agoYikes, I guess you got me. I didn't realize that attempting to piss someone off anonymously for your own amusement was satire. Your ideas intrigue me and I am interested in subscribing to your newsletter.
- smosher 15y agoI was hoping you'd see the irony in my reply. I didn't mean any offense. (Thanks for illustrating my point though.)
- zmitri 15y agoGuys, isn't this just another sorting problem? Aren't you just relying on the thread scheduler to sort them?
- azim 15y agoWhat's interesting is that in theory, assuming an appropriate scaling factor to divide the input by, the time and space complexity for Sleep sort are O(1). This is basically like hashing numbers, then iterating the buckets -- except that the iteration is done over time. Given that, one could envision degenerative cases for which Sleep sort could in theory outperform a standard algorithms like quicksort.
- drobilla 15y agoHilarious, though not strictly correct. There is no guarantee 'sleep n' sleeps for n seconds, or that 'sleep n' wakes up before 'sleep n+1'. Granted, in reality if scheduling is so far off that things like this on the order of seconds become a problem, you've probably got bigger problems...
- Stormbringer 15y agoWow. An order 0 sorting algorithm (it is O(0) not O(n) because it doesn't make _any_ comparisons). Amazing.
- arkem 15y agoJust because a sorting algorithm doesn't use any comparisons doesn't make it O(0). For example Radix Sort (http://en.wikipedia.org/wiki/Radix_sort http://en.wikipedia.org/wiki/Radix_sort) is not a comparison based sort and its complexity is O(k.n) where k is the max size of elements.
- dkersten 15y agoThe OS scheduler still does the comparisons (and sorting). How otherwise would the threads wake up in order if they weren't sorted by somebody?
- ChuckMcM 15y ago4chan discussion aside, the concept here is that you 'sleep' n units of time for each element, where n is linearly related to the lexical relationship of the element to the other elements in the list. The 'aha' was that the resulting threads will 'wake up' or 'return' in lexical order. Basically if you transform set L into the time domain, when collecting it back you get it back sorted. Its a fun result, and as an exercise in systems analysis it can be enlightening to look at the impact of timer resolution, thread creation, and ordering, but ultimately the 'trick' is that you've exploited the 'insertion sort' that the kernel does on sleep events. You could try its close cousin "priority sort" where you create threads where you set the priority of each to be related to the value 'n' of the element, and all fractionally lower than the parent thread (most UNIXes are not that flexible but some realtime OSes are) then as the last step you 'yield' and the threads print out their contents in priority order and poof they are sorted. But again, the sorting happened in the kernel when they got inserted into the runq in priority order.
- joe24pack 15y agoOf course it's brilliant, it just delegates the sorting to the scheduler. The OP on 4chan is ready for a PHB position at a large corporation.
- wtracy 15y agoMany of the posts here and on 4chan have deconstructed the algorithm and proven that it is actually O(n^2) or O(n * lg n) when you include the work done by the operating system's scheduler. However, here's a different perspective to look at this from: What if this were implemented on an FPGA? Let's ignore for a moment that the number of gates needed would increase linearly with the size of the input. I'll also simplify the math by assuming that a list of n numbers contains only values in the range [0 .. n] . Let's further assume that we're only sorting positive integers, and that each job sleeps for x clock cycles (where x in the input number). We could sort a list in O(n) time. Digging even deeper: Quicksort performs an integer comparison followed by a branch O(n lg n) times. Even if your processor can compare two integers in one clock cycle, a branch is probably going to screw up your processor's pipelining and take quite a few clock cycles to execute. So, we're possibly looking at a significant speed increase even before we consider the difference in order of growth. So, assuming a predefined upper bound on the number of items in a list, this just might be a great way to perform hardware-assisted sorts. Thoughts?
- wtracy 15y agoI just realized: We would need a circuit polling each of the jobs to see when they finish, and I don't see how it could poll all of jobs every clock cycle. So I don't see it being possible to achieve the per-cycle resolution I suggested above. Furthermore, the polling circuit would have to poll each of the n tasks n times, leading us finally back to a running time of O(n^2). Still a fun thought experiment, though.
- FlowerPower 15y agoWhy would you poll the tasks? Cant the tasks wake up after their time is done, just fire an interrupt witht he number of the task.
- necubi 15y agoFor hardware based sorting, we can do even better using sorting networks[0]. Sorting networks are comprised of a system of wires, one for each input, and comparators between wires which always output the higher number on the bottom wire and the lower on the top. Using this framework we can do massively parallel sorts with excellent time complexity. The problem is that sorting networks need to be designed for each input size, and designing efficient sorting networks is an open problem. There has been some work in the evolutionary computing community on sorting networks, and some of the best known networks for various sizes were found by EAs, but large networks are still a challenge. [0] http://en.wikipedia.org/wiki/Sorting_network http://en.wikipedia.org/wiki/Sorting_network
- Andi 15y agoDo you see the hidden narrative?
- random42 15y agoI dont think this sort is dependable for sorting floats in close ranges. I tried it with, ./sleepsort.bash 1 1.01 1.01 1.02 and output was 1 1.01 1.02 1.01 Clever hack, nonetheless.
- raymondh 15y agoPython version: http://code.activestate.com/recipes/577756-sleepsort/ http://code.activestate.com/recipes/577756-sleepsort/