Shuffling is the act of randomizing the order of the elements in a collection.

Shuffling is the process by which the order of the elements in a collection is randomized. One effective algorithm for doing so is as follows:

For a zero-based collection of n elements:

  1. i = n
  2. j = random integer between 0 and i (inclusive)
  3. Swap the values of the elements at j and i
  4. i = i - 1
  5. If (i > 0), go to 2

This is called the Fisher-Yates shuffle and has a time complexity of O(n).

history | excerpt history