[LeetCode] Inplace random shuffling an array

来源:互联网 发布:手机地图导航软件 编辑:程序博客网 时间:2024/06/07 23:04
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

0 0