Random Shuffles

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:


algorithm shuffle(x ,n )   // shuffle x 1 ,..., x n
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$ /le$ i , j $ /le$ 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}}$ . $/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}}$ ,
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值