Firstly, I think there is an error in the pseudo-code. In line 4, I believe that there is a boundary error with i = n, as this will require a random number between n + 1 and n. I fixed this later by assuming the code is as follows:
1 PERMUTE-WITH-ALL-IDENTITY(A) 2 n = A.length 3 for i = 1 to n 4 swap A[i] with A[RANDOM(1,n)] 5 swap A[i] with A[RANDOM(i,n)]
If this is code, then I believe that the answer is no, it does not create uniformly random permutations. I have no mathematical proof that this is so, but I do have a piece of C ++ code that translates all possible paths through PERMUTE-WITH-ALL-IDENTITY and counts the number of times that each permutation is done. I ran this code and tested the permutation algorithm on sequences of lengths from 0 to 4, inclusive, and found that not all permutations are equally likely.
Here is the code:
#include <iostream>
This program generates reports that show for each permutation the number of possible execution paths through the algorithm that creates this permutation. The output for permuting the four elements is shown below. Given that each execution path is equally likely, since the numbers here do not match, we can conclude that the algorithm is not uniformly random:
Report for size 4 =================================================== Map entries: 0123: 214 0132: 268 0213: 267 0231: 316 0312: 242 0321: 229 1023: 268 1032: 322 1203: 312 1230: 349 1302: 287 1320: 262 2013: 242 2031: 283 2103: 233 2130: 262 2301: 252 2310: 240 3012: 213 3021: 208 3102: 204 3120: 187 3201: 248 3210: 236 ===================================================
The above analysis depends on the fact that
- My code is correct and
- My interpretation of the pseudocode is correct.
If this is incorrect, I would be happy to cancel or edit this answer. Please let me know if I made a mistake here.
Hope this helps!
source share