const numbers = [1, 5, 7, 46, 31, 54]; // 使用 Fisher-Yates 算法进行数组的随机排序
let count = 0;
function monki(obj) {
for (let i = obj.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[obj[i], obj[j]] = [obj[j], obj[i]];
}
if (!arraysEqual(obj, [1, 5, 7, 31, 46, 54])) {
count++;
monki(obj);
} else {
console.log(obj, count);
}
}
function arraysEqual(a, b) {
if (a === b) return true;
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
if (a[i] !== b[i]) return false;
}
return true;
}
monki(numbers);
一次就能排序成功的猴子排序法,在某些情况下确实是世界上最快的排序法 ~![狗头]