Shuffle algorithm and its proof

Source: Internet
Author: User
Tags shuffle

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.