Random Shuffles

来源:互联网 发布:运动社交软件 推荐 编辑:程序博客网 时间:2024/05/22 00:30

This is more difficult. We have a list (x1,..., xn) and we wantto shuffle it randomly.

The following, surprisingly simple, algorithm does the trick:


algorithm shuffle(x,n)   // shuffle x1,..., xn
begin
  for i = n downto 2 begin
    k = irand(1,i)
    swap over xi and xk
  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 worksif we have some notion of what we mean by a `random shuffle'. Let mekeep things simple and say that a shuffling process is random if eachelement of the list can end up in any position in the list with equalprobability. That is to say, in a list of n items there are npossible places that any given element can eventually occupy. I wanteach of these places to be equally likely.

So we now have to calculate the probability that our algorithm putselement xi into position j, where 1$ /le$i, j$ /le$n. If you lookcarefully at the algorithm you will see that element xi end up inposition j if it is not chosen on the first n - j steps ofthe algorithm and is chosen on the step n - j + 1. Since we knowthat irand(n, m) is genuine we can use elementary methods tofind that the probability of xi ending up in position j is

 $/displaystyle {/frac{n-1}{n}}$ . $/displaystyle {/frac{n-2}{n-1}}$ . $/displaystyle {/frac{n-3}{n-2}}$ ... $/displaystyle {/frac{j}{j+1}}$ . $/displaystyle {/frac{1}{j}}$  = $/displaystyle {/frac{j}{n}}$ . $/displaystyle {/frac{1}{j}}$ = $/displaystyle {/frac{1}{n}}$,
原创粉丝点击