Skip to content

Instantly share code, notes, and snippets.

@st98
Last active August 29, 2015 13:57
Show Gist options
  • Save st98/9875065 to your computer and use it in GitHub Desktop.
Save st98/9875065 to your computer and use it in GitHub Desktop.
JavaScriptでボゴソート。
var randint = function (min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
var swap = function (obj, i, j) {
var tmp;
tmp = obj[i];
obj[i] = obj[j];
obj[j] = tmp;
};
var shuffle = function (obj) {
var i, j, len, result;
result = [].concat(obj);
for (i = obj.length - 1; i > 0; i--) {
j = randint(0, i);
swap(result, i, j);
}
return result;
};
var le = function (a, b) {
return a <= b;
};
var isSorted = function (obj, cmp) {
var i, len;
cmp = cmp || le;
if (len <= 1) {
return true;
}
for (i = 1, len = obj.length; i < len; i++) {
if (!cmp(obj[i - 1], obj[i])) {
return false;
}
}
return true;
};
var bogosort = function (obj) {
var result = [].concat(obj);
while (!isSorted(result)) {
result = shuffle(result);
}
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment