Problem definition:
Given ordered sequence 1-n, it is required to be disturbed so that the probability of each element appearing in any position is 1/n.
Program implementation:
void Shuffle (intint n) // n is the total number of elements in the sequence { int idx; for (int0; i < n; i++) { = rand ()% (i+1); // idx in subscript [0, I] Swap (&arr[idx], &arr[i]);} }
The mathematical induction method proves that:
(1) When n=1, the IDX must be 0, so the element arr[0] in any position of probability is 1/1, the proposition is established.
(2) Assuming that when n=k, the proposition is established, that is, n=k, the probability of any element in the original array at any one position is 1/k.
(3) When the n=k+1, by the above assumptions, when the algorithm executes K times, the first k elements in the first K-position probability are 1/k;
When the last step is taken, the probability that any element of the former K element is substituted to the k+1 position is: (1-1/(k+1)) * 1/k = 1/(k+1);
The probability of any one position in the front K position is (1-1/(k+1)) * 1/k = 1/(k+1);
Therefore, the probability of the first k elements in any position is 1/(k+1);
So, for the first k elements, they have a probability of 1/(k+1) in the position of the k+1.
For the k+1 element, its probability at the original position is 1/k+1, the probability of any position in the first k position is: (1-1/(k+1)) * (1/k) = 1/(k+1), so for the first k+1
The probability of k+1 a position in the entire array is also 1/k+1.
(4) To sum up, for any n, as long as the scheme in accordance with the method, you can meet each element in any one location probability is 1/n.
Shuffle algorithm and its proof