Algorithms · Visualized
Random: Fisher-Yates Shuffle
Randomized Algorithms
Randomness as a tool — shuffles, sampling, and probabilistic selection.
Produces a truly random, unbiased permutation of an array in place. Time: O(n) average, O(n) worst; space: O(1) — shuffles in place.
Big-O: Expected-case guarantees with simple implementations.
Fisher-Yates Shuffle
Randomized AlgorithmsProduces a truly random, unbiased permutation of an array in place. It works backward through the array, and at each position swaps the current element with a randomly chosen element from the remaining unshuffled portion (including itself), guaranteeing every possible ordering is equally likely.
How Fisher-Yates Shuffle Works
- Start from the last index of the array and move toward the first.
- At each position i, generate a random index j such that 0 ≤ j ≤ i (i.e. anywhere from the start up to and including the current position).
- Swap the elements at positions i and j.
- Move to the next position going backward (i - 1) and repeat.
- Once you reach the first position, the array has been shuffled into a uniformly random order.
Fisher-Yates Shuffle Worked Example
Input: [1, 2, 3, 4, 5]
i=4: random j in [0,4], say j=1 → swap → [1,4,3,2,5]. i=3: random j in [0,3], say j=3 → no change. i=2: random j in [0,2], say j=0 → swap → [3,4,1,2,5]. i=1: random j in [0,1], say j=0 → swap → [4,3,1,2,5]. i=0: random j=0 → no change. Final shuffled array: [4,3,1,2,5] (one of many equally likely outcomes).
import random
def shuffle(arr):
a = arr[:]
for i in range(len(a) - 1, 0, -1):
j = random.randint(0, i)
a[i], a[j] = a[j], a[i]
return aBehind the Scenes Execution
Press ▶ Run in the visualizer — the call stack, registers and memory will replay here in sync with the code, line by line.
Fisher-Yates Shuffle Time & Space Complexity
When to Use Fisher-Yates Shuffle
- Shuffling playlists, card decks, or randomized quiz question order — anywhere a genuinely unbiased shuffle is required.
- The gold-standard shuffle algorithm; naive alternatives (like random sort comparators) are provably biased.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Keep the momentum going
Step through a related structure, pattern or course — the ideas reinforce each other and stick faster.