This is more difficult. We have a list (x 1 ,..., x n ) and we want to shuffle it randomly.
The following, surprisingly simple, algorithm does the trick:
begin
for i = n downto 2 begin
k = irand(1,i)
swap over x i and x k
end
end
Why does this work? It seems that it is not doing enough `mixing up' to produce a genuinely random shuffle. We can only prove that it works if we have some notion of what we mean by a `random shuffle'. Let me keep things simple and say that a shuffling process is random if each element of the list can end up in any position in the list with equal probability. That is to say, in a list of n items there are n possible places that any given element can eventually occupy. I want each of these places to be equally likely.
So we now have to calculate the probability that our algorithm puts element x i into position j , where
1 i , j
n . If you look carefully at the algorithm you will see that element x i end up in position j if it is not chosen on the first n - j steps of the algorithm and is chosen on the step n - j + 1. Since we know that
irand(n , m ) is genuine we can use elementary methods to find that the probability of x i ending up in position j is
![$/displaystyle {/frac{n-1}{n}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img39.gif)
![$/displaystyle {/frac{n-2}{n-1}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img199.gif)
![$/displaystyle {/frac{n-3}{n-2}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img200.gif)
![$/displaystyle {/frac{j}{j+1}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img201.gif)
![$/displaystyle {/frac{1}{j}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img202.gif)
![$/displaystyle {/frac{j}{n}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img203.gif)
![$/displaystyle {/frac{1}{j}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img202.gif)
![$/displaystyle {/frac{1}{n}}$](http://www.maths.abdn.ac.uk/%7Eigc/tch/mx4002/notes/img41.gif)