Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Randomly sorting an array

Does there exist an algorithm which, given an ordered list of symbols {a1, a2, a3, ..., ak}, produces in O(n) time a new list of the same symbols in a random order without bias? "Without bias" means the probability that any symbol s will end up in some position p in the list is 1/k.

Assume it is possible to generate a non-biased integer from 1-k inclusive in O(1) time. Also assume that O(1) element access/mutation is possible, and that it is possible to create a new list of size k in O(k) time.

In particular, I would be interested in a 'generative' algorithm. That is, I would be interested in an algorithm that has O(1) initial overhead, and then produces a new element for each slot in the list, taking O(1) time per slot.

If no solution exists to the problem as described, I would still like to know about solutions that do not meet my constraints in one or more of the following ways (and/or in other ways if necessary):

  • the time complexity is worse than O(n).
  • the algorithm is biased with regards to the final positions of the symbols.
  • the algorithm is not generative.

I should add that this problem appears to be the same as the problem of randomly sorting the integers from 1-k, since we can sort the list of integers from 1-k and then for each integer i in the new list, we can produce the symbol ai.

like image 820
Cam Avatar asked Dec 17 '22 18:12

Cam


2 Answers

Yes - the Knuth Shuffle.

like image 92
psmears Avatar answered Jan 21 '23 20:01

psmears


The Fisher-Yates Shuffle (Knuth Shuffle) is what you are looking for.

like image 43
threenplusone Avatar answered Jan 21 '23 22:01

threenplusone