Is there a name for this approach/any info on why it doesn't work?
Is there a name for this approach/any info on why it doesn't work?
Step 1. Swap a, c -> [c,b,a]
Step 2. Swap b, c -> [b,c,a]
Step 3. Swap a, a -> [b,c,a]
What is the probability that we do exactly these steps? At each step, we have 3 choices, so (1/3) * (1/3) * (1/3) = 1/27. What is the probability that we end up with [b,c,a] ? You might think 1/27 as well, but that is not quite true – it is possible, that we choose different steps, but end up with the same result. For example, we can do [a,b,c]->[b,a,c]->[b,c,a]->[b,c,a]. But the probability will always be a multiple of 1/27 – it is just 1/27 times the number of possible paths that leads to [b,c,a].Now, what should the probability be? There are exactly 6 ways to shuffle [a,b,c] (this is the number of permutations, 3! = 3 * 2 * 1 = 6). So we want to get [b,c,a] with a probability of 1/6. But 1/6 is not a multiple of 1/27 ! (You can see that by looking at the equation 1/6 = x/27, which is the same as x = 27 / 6 = 4.5 .)
The same argument works for any length n > 2, as n*n is not divisible by n-1, but n! is.
Base case: n=1. Obvious.
Inductive step: n>1. The nth element swaps to itself w/ prob 1/n, and to any other element w/ prob 1/n. By induction the other elements have been uniformly shuffled. Any of those elements is swapped to the nth place w/ prob 1/n.
This proves that
for i in range(min_key,max_key):
swap(arr, i, choice(i, max_key))
works as a shuffle, by growing a random sub-array.*The first algorithm was
for i in range(min_key,max_key):
swap(arr, i, choice(min_key, max_key))
which has different biases.* I am not actually sure that this actually works.