It is not hard to shuffle an array
in O(n), with in place swapping,
How to do it for list
in OCaml, with O(n)?
Requirement:<
You could mimick the riffle shuffle for cards.
A riffle shuffle of a deck of cards means to:
It is actually easier to do the reverse permutation:
According to "Mathematical developments from the analysis of riffle shuffling, by Persi Diaconis, 2002", choose k = 3/2 log_2(n) + c. Indeed, the total variation distance between uniformity and the result falls exponentially fast to 0: it is approximately halved each time you increment c. You could choose c=10.
Space O(1) (if you destroy L), time O(n log n). But there are O(n log n) calls to the random generator, while Jeffrey Scofield's solution only needs O(n) random bits, but Θ(n) space.