[LeetCode] Inplace random shuffling an array

public void shuffle(int[] A) {
    if (A == null || A.length == 0) return;
    for (int i = 0; i < A.length-1; ++i) {
        int random = Math.random()*(A.length-i) + i;
        int temp = A[i];
        A[i] = A[random];
        A[random] = temp;
    }
}

justification: Mostly from Here

For each element, it has same probability to go to each position

Step 1. The probability that ith element (including the first one) goes to first position is 1/n, because we randomly pick an element in first iteration.

Step 2. The probability that ith element goes to second position (position 1) can be proved to be 1/n by dividing it in two cases.
Case 1: for the 1st element (position 0)
Probability that the 1st element was switch with the second element in the previous step, thus it’s now at the second position
Case 2: i <= i < n (index of non-first):
The probability of ith element going to second position = (probability that ith element is not picked in previous iteration) x (probability that ith element is picked in this iteration)
So the probability = ((n-1)/n) x (1/(n-1)) = 1/n

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值