mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
19 lines
394 B
JavaScript
19 lines
394 B
JavaScript
export const shuffle = (array) => {
|
|
let maxLength = array.length
|
|
let temp
|
|
let idx
|
|
|
|
// While there remain elements to shuffle...
|
|
while (maxLength) {
|
|
// Pick a remaining element...
|
|
idx = Math.floor(Math.random() * maxLength--)
|
|
|
|
// And swap it with the current element
|
|
temp = array[maxLength]
|
|
array[maxLength] = array[idx]
|
|
array[idx] = temp
|
|
}
|
|
|
|
return array
|
|
}
|