神奇的SleepSort

最强的排序算法是什么?快排?桶排?nonono,都不是。今天在一外国论坛上看到一种神奇的排序算法,它的时间复杂度是O(n),空间复杂度为O(0),时间复杂度完爆了快排,空间复杂度完爆了hash,并且还是稳定排序!实在是逆天啊。

原帖地址:http://dis.4chan.org/read/prog/1295544154

1 #!/bin/bash
2  
3  function f() {
4 sleep "$1"
5 echo "$1"
6 }
7 while [ -n "$1" ]
8 do
9 f "$1" &
10 shift
11 done
12 wait

example usage:./sleepsort.bash 5 3 6 3 6 3 1 4 7

这是它的shell版本,其思想是根据每个数的大小,用不同的线程sleep不同时间,再将其输出。最后,再附上本人的java版本的代码:

1 public class SleepSort{
2 public static void main(String[] args) {
3 int array[] = {3,2,1,5,6,2,4,6,8,9,0,10};
4 SleepSortThread[] threads = new SleepSortThread[array.length];
5 for (int i = 0; i<array.length; i++) {
6 threads[i] = new SleepSortThread(array[i]);
7 threads[i].start();
8 }
9 }
10
11 static class SleepSortThread extends Thread {
12 int base_time = 10;
13 int num;
14
15 public SleepSortThread(int num) {
16 super("sleep_sort_"+num);
17 this.num = num;
18 }
19
20 public void run() {
21 try {
22 Thread.sleep(num*base_time);
23 System.out.print(num+" ");
24 } catch (InterruptedException e) {
25 }
26 }
27 }
28 }

posted @ 2011-06-17 20:00  影の心  阅读(973)  评论(6编辑  收藏  举报