Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step
https://juejin.cn/column/7244788137410560055
2.03k stars 235 forks source link

数组乱序(时间复杂度O(n)) #508

Open Sunny-117 opened 7 months ago

Lupengcheng7 commented 3 months ago
function shuffle(array){
    for(let i = array.length - 1; i>=0; i--){
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }

    return array
}

// 测试
const arr = [1, 2, 3, 4, 5];
const shuffledArr = shuffle(arr);
console.log(shuffledArr);