imashutosh51

Fisher–Yates Shuffle (All Permutations Equally Likely)

Apr 16th, 2026 (edited)
43
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. """
  2. Given an array of n elements, randomly shuffle the array such that every possible permutation has equal probability of occurring.
  3.  
  4. The shuffle must be done efficiently in-place using O(1) extra space and O(n) time.
  5.  
  6. Shuffles the array in-place using the Fisher–Yates algorithm (forward version).At each step, we pick a random element only from the part of the array that has not been shuffled yet and place it at the current position.
  7.  
  8. A common doubt is: “Later positions have fewer choices, so is it unfair?” -> It is actually fair because when initial numbers got swapped, it might have also gone to later part which make each numbers probability to be on any position is same.
  9. """
  10.  
  11. import random
  12. def shuffle_forward(arr):
  13.     n = len(arr)
  14.    
  15.     for i in range(n):
  16.         j = random.randint(i, n-1)  # pick from i to n-1
  17.         arr[i], arr[j] = arr[j], arr[i]
  18.    
  19.     return arr
Advertisement
Add Comment
Please, Sign In to add comment