Ramdon Shuffle

Random ShuffleShuffle SortLinear ShuffleAlgorithmProofA Common MistakeRandom ShuffleGoal. Rearrange array so that result is a uniformly random permutation. (洗牌算法)Shuffle Sort使用排序算法来shuffle:Gener
摘要由CSDN通过智能技术生成

Random Shuffle

Goal. Rearrange array so that result is a uniformly random permutation.
(洗牌算法)

Shuffle Sort

使用排序算法来shuffle:

  • Generate a random real number for each array entry.
  • Sort the array. (以随机数为key来排序,每个item和对应的随机数一起exchange)

分析: 复杂度为 O(nlogn)

Linear Shuffle

Algorithm

O(n) 复杂度的shuffle算法——Fisher–Yates shuffle (Knuthe shuffle)。

  • In iteration i , pick integer r between 0 and i uniformly at random.
  • Swap a[i] and a[r].

Pseudo-code:

/*
Input: an array a of length n.
Output: an shuffled array a.
*/
For i = 0 to n-1
    r = random number that in [0,i]
    swap a[i] and a[r]

或者从后往前循环(Knuth-Durstenfeld Shuffle)

To shuffle an array a of n elements (indices 0..n-1):
  for i from n − 1 downto 1 do
       j ← random integer such that 0 ≤ j ≤ i
       exchange a[j] and a[i]



Java code. ( From Algorithm 4th.)

public static void shuffle(Object[] a)
{
    int N = a.length;
    for (int i = 0; i < N; i++)
    {
        // generate random number between 0 and i
        int r = StdRandom.uniform(i + 1);
        exch(a, i, r);
    }
}

注意: 产生随机数的范围为 [0,i] ,而不是 [0,n1]

Proof

Proposition. [Fisher-Yates 1938] Fisher-Yates shuffling algorithm produces a
uniformly random permutation of the input array in linear time.

Proof.1
S[1],S[2],,S[n] 来表示array中的n个元素,为证明该命题,只需证明如下引理

Lemme. The list of elements (S[1],,S[n]) at the end of the algorithm can be any of the n!
permutations with the same probability.
即, (S[1],,S[n]) 在算法结束时,可以等概率地生成所有 n! 排列中的任何一个。

使用归纳法来证明:
当算法完成 i=k(1kn) 次循环后,数组 (S[1],,S[k]) 可以等概率地生成所有 k! 排列中的任何一个。

  • i=1 时,只有
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值