Is it possible to shuffle elements of an n-sized array uniformly, i.e. the probability of any of the n! combinations occurring is the same, in expected O(n)
time. How so?
I have to shuffle elements of A
to a new array B
The first thing that comes to my mind when I'm trying to do this is just picking a random number i
from 1 to n, see if A[i]
has already been picked, if so, then repeat, otherwise put A[i]
in the first available position in B
.
However, this coupon collector problem has expected time O(n log n)
.
Can someone suggest an O(n)
expected time algorithm.
Thanks.