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

前端 未结 12 1641
广开言路
广开言路 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:19

    I did some measurements of how random the results of this random sort are...

    My technique was to take a small array [1,2,3,4] and create all (4! = 24) permutations of it. Then I would apply the shuffling function to the array a large number of times and count how many times each permutation is generated. A good shuffling algoritm would distribute the results quite evenly over all the permutations, while a bad one would not create that uniform result.

    Using the code below I tested in Firefox, Opera, Chrome, IE6/7/8.

    Surprisingly for me, the random sort and the real shuffle both created equally uniform distributions. So it seems that (as many have suggested) the main browsers are using merge sort. This of course doesn't mean, that there can't be a browser out there, that does differently, but I would say it means, that this random-sort-method is reliable enough to use in practice.

    EDIT: This test didn't really measured correctly the randomness or lack thereof. See the other answer I posted.

    But on the performance side the shuffle function given by Cristoph was a clear winner. Even for small four-element arrays the real shuffle performed about twice as fast as random-sort!

    // The shuffle function posted by Cristoph.
    var shuffle = function(array) {
        var tmp, current, top = array.length;
    
        if(top) while(--top) {
            current = Math.floor(Math.random() * (top + 1));
            tmp = array[current];
            array[current] = array[top];
            array[top] = tmp;
        }
    
        return array;
    };
    
    // the random sort function
    var rnd = function() {
      return Math.round(Math.random())-0.5;
    };
    var randSort = function(A) {
      return A.sort(rnd);
    };
    
    var permutations = function(A) {
      if (A.length == 1) {
        return [A];
      }
      else {
        var perms = [];
        for (var i=0; i
        

提交回复
热议问题