Randomizing an array

Everyone who has studied computer science has come across sorting algorithms, but how do you unsort? In programs involving randomizing the order of a known group of items — shuffling a pack of cards for instance — this is crucial. Now, you may think the best way to randomly pick values from an array of N elements is to generate random indices between 0 and N-1 to reference the array at random. However, you need some mechanism to prevent picking the same element twice. The best thing to do is to randomize the whole array using the following algorithm, which was invented in the 1950’s by two computer scientists called Fisher and Yates.

The Fisher-Yates Shuffle

To shuffle an array a of n elements:
  for i from n−1 to 1
       j ← random integer with 0 ≤ ji
       exchange a[j] and a[i]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s