Shuffling algorithm Fisher-Yates shuffle

Source: Internet
Author: User

Returns a random number between 1-N in the int rand (int n) function. How to disrupt array a [n?

The original Fisher-Yates algorithm opened another array B [N] and put the expected a [n] in B [N]. The steps are as follows:

Set I = 0

1. Generate a random number k between 1-a.length

2. Place a [k] to B [I] to remove a [k] And I ++ from array.

3. If a. length> 0, go to step 1.

This algorithm needs to remove the number in a and shift each time, so the algorithm complexity is O (n ^ 2 ).

For example, an algorithm process is as follows:

Random Number range Random Number A B
    1 2 3 4 5 6 7 8  
Random Number range Random Number A B
1-8 3 1 234 5 6 7 8 3
Random Number range Random Number A B
1-7 4 1 23456 7 8 3 5
Random Number range Random Number A B
1-6 5 1 2345678 3 5 7
1-5 3 1 23 4 5678 3 5 7 4
1-4 4 1 23 4 567 8 3 5 7 4 8
1-3 1 123 4 567 8 3 5 7 4 8 1
1-2 2 123 4 5 6 7 8 3 5 7 4 8 1 6
    1 2 3 4 5 6 7 8 3 5 7 4 8 1 6 2
Later, the algorithm was improved. Instead of opening an array, it switched the elements above array a to achieve the shuffling.

This algorithm has two versions, the same principle:

Version 1:

For (INT I = N; I> = 1; -- I) {Int J = rand (I); // generates a random number exchange (A [I], A [J]); // exchange a [I], a [J]}

Version 2:

For (INT I = 1; I <= N; + I) {Int J = (RAND (N)/n) * (N-I + 1) + I-1; // generate a random number exchange (A [I], a [J]) between I-n; // exchange a [I], a [J]
A calculation process of version 1 is as follows:

Random Number range random number AA (sorted) 1-861 2 3 4 5 87 6

Random Number range Random Number A A (sorted)
1-7 2 173 4 5 8 26
Random Number range Random Number A A (sorted)
1-6 6 1 7 3 4 5 82 6
1-5 1 57 3 4 18 2 6
1-4 3 5 74 31 8 2 6
1-3 3 5 7 43 1 8 2 6
1-2 1 7 54 3 1 8 2 6

Reference: http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

Shuffling algorithm Fisher-Yates shuffle

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.