9

I am not sure whether the following pseudo-code can generate an uniformly random permutation:

PERMUTATE(A): 
    n = A.length
    for i = 1 to n
        swap A[i] and A[random(1,n)]

It seems to be right, but can anyone give me a rigorous proof to verify its correctness or wrongness ?

Flybywind
  • 968
  • 1
  • 11
  • 23

1 Answers1

20

This solution is biased, you want the Fisher Yates algorithm [which is similar] for non biased permutation. [basically, you need to swap with random(i,n) instead of with random(1,n)]

This thread discusses how and why your solution is biased.

Community
  • 1
  • 1
amit
  • 175,853
  • 27
  • 231
  • 333