A clever solution found on the Internet:

Array.prototype.shuffle = function() {
    return this.sort(function(a, b) {
      return Math.random() > 0.5 ? -1:1
    });
}
Copy the code

Very clever, using random number to control the sort of function, to achieve the purpose of out-of-order. The time is order nlogn.

I also used Math.random and quickly wrote a shuffle with O(n) :

Array.prototype.shuffle = function() {
    if(this.length <= 1) return this
    const array = this, length = this.length
    for(let i = 0; i < length; i++) {
        let temp = array[i]
        let count = Math.floor((length - 1) * Math.random())
        array[i] = array[count]
        array[count] = temp
    }
   return array
}

/ / the second edition
Array.prototype.shuffle = function() {
    if(this.length <= 1) return this
    const array = this, length = this.length
    for(let i = 0; i < length; i++) {
        let temp = array[i]
        let count = Math.floor(length * Math.random())
        array[i] = array[count]
        array[count] = temp
    }
   return array
}
Copy the code

Why length-1? Because I initially thought math. ramdom was in the range [0,1], so I had to deal with bounds. It didn’t feel right, so I went to MDN and found that math. ramdom’s true value range was (0,1), which meant that it was impossible to get to the boundary value, so I dropped -1 and that was version 2.

I went to the Internet and they wrote it like this:

Array.prototype.shuffle = function() {
    if(this.length <= 1) return this
    const array = this, length = this.length
    for(let i = 0; i < length; i++) {
        let temp = array[i]
        let count = Math.floor((i + 1) * Math.random())
        array[i] = array[count]
        array[count] = temp
    }
   return array
}
Copy the code

Not particularly understand why coefficient and I hook, so the limitations of previous transposition is very big, is not a global random exchange, such as I = 0 count must be 0, then the cycle no sense, although when I gradually increase the randomness also increases, but why don’t you speak I set to constant big enough?