JavaScript Snippet

Shuffle an Array (Fisher-Yates)

Difficulty: Easy

The naive `array.sort(() => Math.random() - 0.5)` looks fine until you measure it: the distribution is heavily biased and some pairs swap with much higher probability than others. The Fisher-Yates shuffle is the standard correct answer in O(n) time with uniform output. This snippet shows the in-place version, a non-mutating wrapper, and an empirical demo of why the popular `sort`-based trick is biased.

Code Snippets
/

Shuffle an Array (Fisher-Yates)

Shuffle an Array (Fisher-Yates)

The naive `array.sort(() => Math.random() - 0.5)` looks fine until you measure it: the distribution is heavily biased and some pairs swap with much higher probability than others. The Fisher-Yates shuffle is the standard correct answer in O(n) time with uniform output. This snippet shows the in-place version, a non-mutating wrapper, and an empirical demo of why the popular `sort`-based trick is biased.

JavaScript
Easy
3 snippets
arrays
code-template
array-manipulation-patterns

1,068 views

7

The Fisher-Yates shuffle walks the array from the end and at each position picks a random index in [0, i], then swaps. The crucial detail is that the random range shrinks each step (i + 1), which is what gives every permutation an equal probability. Anything that picks from [0, length) for every iteration produces a biased distribution. The algorithm is O(n) time, O(1) extra space, and is the textbook correct shuffle. We verify by sorting a copy and confirming the original elements are preserved.