分享

神级排序算法:sleep sort

 askjc 2013-11-21

 

下面是一个排序算法,用shell实现的:

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

用法:

 

 

./sleepsort.sh 5 3 6 3 6 3 1 4 7

 

这个算法太NB、太BT、太搞笑了!

神马冒泡、插入、归并...  全是浮云啊!

膜拜吧!

 

详情可见酷壳原文:http:///articles/4883.html

 

佩服之余,我在linux下用C语言实现了一把:

 

  1. //sleepsort.c  
  2. #include <stdio.h>  
  3. #include <unistd.h>  
  4. #include <pthread.h>  
  5. void *f(void *opt)  
  6. {  
  7.     sleep((*((int *)opt)));  
  8.     printf("%d,",(*((int *)opt)));  
  9.     pthread_exit(0);  
  10. }  
  11. int main()  
  12. {  
  13.     const int len=5;  
  14.     pthread_t a_thread[5];  
  15.     int array[5]={3,5,2,4,1};  
  16.     int i=0;  
  17.   
  18.     while(i<len)  
  19.     {  
  20.     pthread_create(&(a_thread[i]),NULL,f,&(array[i]));  
  21.     i++;  
  22.     }  
  23.     i=0;  
  24.     while(i<len)  
  25.     {  
  26.     pthread_join(a_thread[i],0);  
  27.     i++;  
  28.     }  
  29.     printf("/n");  
  30.   
  31.     return 0;  
  32. }  

 

编译:

gcc  -Wall  -o  sleepsort  sleepsort.c   -lpthread

执行:

./sleepsort

结果:

1,2,3,4,5,

 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多