The Fisher-Yates Shuffle
We’ve looked at several different sorting algorithms, but now let’s turn our focus to an unsorting algorithm. While sorting makes order out of chaos, shuffling makes chaos out of order.
To shuffle an array, Python uses a variant of an algorithm known as the Fisher-Yates Shuffle, which was named after Ronald Fisher and Frank Yates, who first described it in 1938. This was before computers, so their original description involved using pencil and paper. Here’s how it works as a computerized algorithm:
-
We point to the first index of the array. We’ll eventually point to the others, too, but we start at the beginning. We’ll call this the “current index.”
-
We generate a random (or pseudorandom) number to choose a random index ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access