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]); |
试了试 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
真的很有趣,搜了一下,发现已经存在的了。http://zh.wikipedia.org/wiki/Bogo%E6%8E%92%E5%BA%8F