jyzwf / blog

在Issues里记录技术得点滴
17 stars 3 forks source link

洗牌算法 #34

Open jyzwf opened 6 years ago

jyzwf commented 6 years ago

洗牌算法可以将一组数据变得随机无序,具体的过程如下:

image

时间复杂度是 O(n)

注:Math.random() 函数返回一个浮点, 伪随机数在范围 [0,1)

js 的实现:

var shuffle = function (array) {
    let length = array.length,
        randomIdx,
        tempVal;

    for (var i = length - 1; i >= 0; i--) {
        randomIdx = Math.floor(Math.random() * (i + 1));
        tempVal = array[randomIdx]

        array[randomIdx] = array[i]
        array[i] = tempVal
    }

    length = randomIdx = tempVal = null

    return array
}

shuffle([1,2,3,4,5,6,7,8])    // [4, 1, 2, 7, 8, 3, 6, 5]
shuffle([1,2,3,4,5,6,7,8])    // [8, 3, 7, 2, 5, 1, 6, 4]