No, your algorithm cannot give homogeneous distribution of possible permutations. See the explanation of the similar error in the section "Implementation errors":
This can be seen from the fact that doing so yields nn distinct
possible sequences of swaps, whereas there are only n! possible
permutations of an n-element array...
Your case is a little different, but the same logic can be applied. On each iteration step you generate two randoms (0...n-1
), so there are n * n
possible array changes that can be applied. You do this n
times. So, the total number of paths that you can go with equal probability is (n * n)
n
, but there are n!
possible permutations.
For example, you have three elements. On each step there are 3 * 3 = 9
ways to change your current state. Doing that three times gives 9 * 9 * 9 = 729
possible ways to change initial array. It would be perfect to have equal number of all possible permutations in that set. However, there are 3! = 6
possible different final results. The number of generated permutations 729
is not divisible by 6
. So for sure some permutations have higher chance to be chosen.
For proper Java implementations of the modern version of the Fisher–Yates shuffle see for example Random shuffling of an array