天才排序算法:睡眠排序(一)

2014-11-24 11:20:09 · 作者: · 浏览: 10
今天看到一个帖子,帖名叫《Genius sorting algorithm: Sleep sort》。看过之后感觉虽然实用价值不高,但挺受启发的,帖上来给大家分享下。
楼主:
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
再帖几个其他常用版本,以便擅长不同语言的朋友 阅读
JAVA版:
[java]
public class SleepSort {
public static void main(String[] args) {
int[] ints = {1,4,7,3,8,9,2,6,5};
SortThread[] sortThreads = new SortThread[ints.length];
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i] = new SortThread(ints[i]);
}
for (int i = 0; i < sortThreads.length; i++) {
sortThreads[i].start();
}
}
}
class SortThread extends Thread{
int ms = 0;
public SortThread(int ms){
this.ms = ms;
}
public void run(){
try {
sleep(ms*10+10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(ms);
}
}
PHP版:
[php]
< php
$pids = array();
for ($i=1; $i<$argc; $i++)
{
if (($pid = pcntl_fork()) == 0)
{
$sleep = intval($argv[$i]);
sleep($sleep);
echo $sleep."\n";
exit();
}
else if ($pid == -1)
{
die();
}
else
{
$pids[] = $pid;
}
}
foreach($pids as $pid)
pcntl_waitpid($pid, $status);
>
php sleepsort.php 1 3 5 6 2
JS版:
[java script]
// Javascript
function lazySort(list, callback) {
var result = [];
list.forEach(function(i) {
setTimeout(function() {
result.push(i);
if(result.length == list.length) {
callback(result);
}
}, i);
});
}
lazySort([4,5,7,1,2,4,5], alert);
Ruby版:
[ruby]
ARGV.each { |e| fork { sleep(e.to_f/1000); puts e } }
还有很多冷门语言版本,感兴趣朋友可以点文后的链接
该贴有1000+回复,我挑几个有趣的回复分享下:
路人A:
Oh god, it works.
But I don't like to wait 218382 seconds to sort '(0 218382)
哦,春哥,它居然能用,但我不想用218382秒去排(0 218382)
路人B:
If the difference between any two of the numbers is too small, race conditions will fuck you up the ass.
如果两个数之间的差距太小,竞态条件就要爆你菊花了。
路人C:
What about
./sleepsort -1 -2 -3
If you slept exp(n) instead of n it could easily include negative integers too!
排-1 -2 -3怎么办?如果你睡exp(n)而不是n,它就能包含负数了。
路人D:
Someone email this to Knuth
你可以给Knuth发邮件了
路人E:
I think thats brilliant :)
Would be fun to design a hardware sorter, based on this..
这招挺高,可以根据这个设计一个硬件排序器
路人F:
This has a best case O(n) and an infinity high worst case. (because its 0(n * Constant) and the constant could be much greater than n)
它有一个最好的O(n)的时间复杂度和一个无穷大的最坏复杂度,因为这个常数可能比n大的多的多
路人G:
I heartily disagree with all the attempts to downplay the brilliance of the sleep sort algorithm. Many of you have missed the important point that while traditional sorti