Книга: A Common-Sense Guide to Data Structures and Algorithms in Python, Volume 2 (for True Epub)
Назад: The Fisher-Yates Shuffle
Дальше: The Efficiency of the Fisher-Yates Shuffle

The Fisher-Yates Shuffle in Action

Let’s visually walk through the Fisher-Yates Shuffle algorithm for the array [1, 2, 3, 4, 5].

Step 1: We point to the first index in the array:

pointing to the array's index 0

Step 2: We randomly choose one of the indexes from our pointer and rightward. For now, this can be any index of our array.

We’ll indicate the random index with a die. Say that our randomly chosen number is a 3:

we roll the die and get a 3

The number the die lands on represents the index that we’re going to swap with. In this case, the index is 3 (and that slot happens to contain the value 4). In the diagram, I’ve placed the die under its corresponding index.

Step 3: We then swap the values of the current index (the arrow) and the random index (the die):

swapping the 1 and the 4

Step 4: We point to the next index of the array:

pointing to the array's index 1

Step 5: We randomly choose a number between 1 and 4 inclusive since we’re choosing an index from the current pointer and to the right. Say we roll a 4:

we roll the die and get a 4

Step 6: We swap the values:

swapping the 2 and the 5

Step 7: We point to the next value:

pointing to the array's index 2

Step 8: We pick a random value from 2 to 4. Let’s say that our computer chooses a 2:

we roll the die and get a 2

Step 9: In this case, we “swap” the value at index 2 with itself, leaving us with the same array as before.

Step 10: We point to the next value:

pointing to the array's index 3

Step 11: We choose a random index. At this point, there are only two to choose from, 3 and 4. Let’s say we roll a 4:

we roll the die and get a 4

Step 12: We swap the current index’s value with the random index’s value:

swapping the 1 and the 2

There’s no point in moving our pointer to the final index. Remember, according to this algorithm, we only swap a value with either itself or any value to its right. Since the final value can’t be swapped with anything other than itself, we end our shuffle here:

the array is fully shuffled

Code Implementation: The Fisher-Yates Shuffle

Here’s a Python implementation of the Fisher-Yates Shuffle:

 import​ ​random
 
 
 def​ ​fisher_yates​(array):
 for​ i ​in​ range(0, len(array) - 1):
  j = random.randint(i, len(array) - 1)
  array[i], array[j] = array[j], array[i]
 
 # Testing out our code:
 array = [1, 2, 3, 4, 5, 6, 7, 8]
 fisher_yates(array)
 print​(array)

Note that our loop stops before len(array) - 1 since we aren’t going to perform a swap for the final index.

Назад: The Fisher-Yates Shuffle
Дальше: The Efficiency of the Fisher-Yates Shuffle