Is it correct to use JavaScript Array.sort() method for shuffling?

前端 未结 12 1624
广开言路
广开言路 2020-11-22 03:48

I was helping somebody out with his JavaScript code and my eyes were caught by a section that looked like that:

function randOrd(){
  return (Math.round(Math         


        
12条回答
  •  你的背包
    2020-11-22 04:37

    It's been four years, but I'd like to point out that the random comparator method won't be correctly distributed, no matter what sorting algorithm you use.

    Proof:

    1. For an array of n elements, there are exactly n! permutations (i.e. possible shuffles).
    2. Every comparison during a shuffle is a choice between two sets of permutations. For a random comparator, there is a 1/2 chance of choosing each set.
    3. Thus, for each permutation p, the chance of ending up with permutation p is a fraction with denominator 2^k (for some k), because it is a sum of such fractions (e.g. 1/8 + 1/16 = 3/16).
    4. For n = 3, there are six equally-likely permutations. The chance of each permutation, then, is 1/6. 1/6 can't be expressed as a fraction with a power of 2 as its denominator.
    5. Therefore, the coin flip sort will never result in a fair distribution of shuffles.

    The only sizes that could possibly be correctly distributed are n=0,1,2.


    As an exercise, try drawing out the decision tree of different sort algorithms for n=3.


    There is a gap in the proof: If a sort algorithm depends on the consistency of the comparator, and has unbounded runtime with an inconsistent comparator, it can have an infinite sum of probabilities, which is allowed to add up to 1/6 even if every denominator in the sum is a power of 2. Try to find one.

    Also, if a comparator has a fixed chance of giving either answer (e.g. (Math.random() < P)*2 - 1, for constant P), the above proof holds. If the comparator instead changes its odds based on previous answers, it may be possible to generate fair results. Finding such a comparator for a given sorting algorithm could be a research paper.

提交回复
热议问题