Created
September 30, 2013 03:19
-
-
Save wintercn/6758985 to your computer and use it in GitHub Desktop.
假期前小玩意,ad-hoc排序
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function shuffle(array){ | |
for(var i = array.length-1; i > 0; i--) { | |
var rnd = Math.floor(Math.random() * (i+1)); | |
var tmp = array[i]; | |
array[i] = array[rnd]; | |
array[rnd] = tmp; | |
} | |
} | |
function isInOrder(array) { | |
for(var i = 0; i < array.length-1; i++) | |
if(array[i]>array[i+1]) | |
return false; | |
return true; | |
} | |
function adhocSort(array){ | |
while(!isInOrder(array)) | |
shuffle(array); | |
return array; | |
} | |
adhocSort([3,2,1,6,7]); |
这不是猴子排序么。。。。。。。猴子排序
烧机好代码,只需5秒,顺利占用3G内存
@bokeyy 事实胜于雄辩
@fatbigbright 最好n 最差无穷 平均 n*n!
谢谢指教!!@wintercn
@bokeyy
这个相当于洗牌,一副牌拿在手上洗,张数一定,洗若干次,总会有那么一次洗出的牌是排好序的。
也可以这样理解,麻将骰子,根据概率学,1至6出现的机率是一样的,掷六次,是有可能连续掷出1至6排好序的
这代码估计机子瞬间秒表
可以试试这组 [3,2,1,6,7,101,23,67,98,23,567,343,2456]
好雅兴!
@wintercn 谁说的?就加了几个数字…… 结果测试的时候 chrome 为之死掉四次
中国好排序。不卡机就可以去买彩票。
@bokeyy 就是如此啊 这算法复杂度太高了 但是不是很有趣么?
真的很有趣,搜了一下,发现已经存在的了。http://zh.wikipedia.org/wiki/Bogo%E6%8E%92%E5%BA%8F
试了试 adhocSort([3,2,1,4,5,11,12,23,24,6,23,7]); 花了43秒 ^_^
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
高端。。。时间复杂度随机。。。。