Shuffling
Shuffling is a procedure used to randomize an array.
The key property is that each item should have an equal probability to end up in any index.
Solution
The recommended (simple) algorithm is the Fisher–Yates shuffle
. Its time complexity is O(n)
. It can even be done inplace.
You go from 0 - (n-1)
and at each index i
pick a random number between 0
- n-i
and move the element at the result into the i + thisRandomNumber
th location in the array.
Maintains Key Property
It maintains that key property as:
Has complexity O(n)
O(n)
Remember random number generation / assiging an item to an array is O(1)
, so its just n
iteration of O(1)
Code
Last updated