How shuffle from random works in Python?
I ask because it works very fast. When I try to write shuffle it works 1 minute for 10^6 element, but Python shuffle does that in 8 sec?
pythonrandom
How shuffle from random works in Python?
I ask because it works very fast. When I try to write shuffle it works 1 minute for 10^6 element, but Python shuffle does that in 8 sec?
Best Answer
Python's
random.shuffle
uses the Fisher-Yates shuffle, which runs in O(n) time and is proven to be a perfect shuffle (assuming a good random number generator).It iterates the array from the last to the first entry, switching each entry with an entry at a random index below it.