Modern Fisher-Yates algorithm for shuffling array

JavaScript Algorithm

One of the optimal algorithm for generating permutation (shuffling) a sequence is Fisher-Yates algorithm. It runs in linear runtime and shuffles in place i.e no additional memory is needed.

Suppose we have an array list=['A', 'B', 'C', 'D', 'E', 'F', 'G'] containing 7 elements. The modern Fisher-Yates algorithm follows the given steps-

  • We start from the end i.e at index 6, so G is selected.
  • A random number between index 0 and 6 is chosen, suppose the number is 2
  • The value at index 2 and 6 are swapped and after first iteration list=['A', 'B', 'G', 'D', 'E', 'F', 'C']
  • This procedure is repeated for other values in the list.
function shuffleArray(arr) {
  for(let i = arr.length - 1; i > 0; i--) {
    let randomIdx = Math.floor(Math.random() * i)
    [arr[i], arr[randomIdx]] = [arr[randomIdx], arr[i]]
  }
  return arr
}