Skip to content

Instantly share code, notes, and snippets.

@wintercn
Created September 30, 2013 03:19
Show Gist options
  • Save wintercn/6758985 to your computer and use it in GitHub Desktop.
Save wintercn/6758985 to your computer and use it in GitHub Desktop.
假期前小玩意,ad-hoc排序
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]);
@zengqifeng
Copy link

中国好排序。不卡机就可以去买彩票。

@wintercn
Copy link
Author

@bokeyy 就是如此啊 这算法复杂度太高了 但是不是很有趣么?

@linkkingjay
Copy link

真的很有趣,搜了一下,发现已经存在的了。http://zh.wikipedia.org/wiki/Bogo%E6%8E%92%E5%BA%8F

@hheedat
Copy link

hheedat commented Oct 2, 2013

试了试 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