Array shuffling algorithm-shuffle

Source: Internet
Author: User
Tags shuffle

Array shuffling, the most recent direct idea is to randomly take an element from an array and put it in another array, but the elements to be removed are duplicated, and a certain way must be ensured:

1. Elements cannot be duplicated
2. The probability of the element being extracted is equal, namely randomness

There are two classical algorithms of array shuffling:

1. Fisher-yates Shuffle (complexity (N^2))

The deletion of the array and the new copy array are both time-and space-consuming.

JavaScript implementation

function Fyshuffle (arr) {    var copy = [],        = arr.length,        N;      while (len)         = Math.floor (Math.random () * len--);        Res.push (Arr.splice (n,1) [0]);    }     return copy;}

2. Knuth-durstenfeld Shuffle (n), an improved version of the fisher-yates algorithm)

kd method is a In-place replacement method, saving space, performance, and randomness, Python built-in random.shuffle used this algorithm.

JavaScript implementation

function Kdshuffle (arr) {    var len = arr.length,        i,temp;      while (len) {        = Math.floor (Math.random () * len--);         = Arr[i];         = Arr[len];         = temp;    }     return arr;}

Reference: http://www.cnblogs.com/Wayou/p/fisher_yates_shuffle.html
Http://www.cnblogs.com/tudas/p/3-shuffle-algorithm.html

Array shuffling algorithm-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.