3
\$\begingroup\$

Based on the standard implementation of Array.sort in JavaScript, would the following be a reasonable way of shuffling the contents of an array? Is it moderately efficient and will it produce a fairly even spread of results?

Array.prototype.shuffle = function () {
 return this.sort(function(){ return Math.random() - 0.5;});
};
palacsint
30.3k9 gold badges82 silver badges157 bronze badges
asked Dec 27, 2011 at 17:39
\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

This article says that a test run on that algorithm showed a bias with items less likely to move farther away from their original location than near (a bias).

My own intuition says that it could cause issues because the .sort() algorithm expects that when a given two elements are compared they will always have the same comparison result and yet that is not true when using this function. Therefore, I'm thinking that how well this work could also depend upon how the .sort() method was actually implemented internally.

This article shows what seems to me like a better algorithm for randomness, though I wouldn't expect it to be particularly efficient:

Array.prototype.shuffle = function() {
 var s = [];
 while (this.length) s.push(this.splice(Math.random() * this.length, 1));
 while (s.length) this.push(s.pop());
 return this;
}

EDIT: Also just found this same question here: https://stackoverflow.com/questions/962802/is-it-correct-to-use-javascript-array-sort-method-for-shuffling. That answer suggests this which is based on the Fisher-Yates algorithm and would be a lot more efficient than the algorithm above:

function shuffle(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;
}

And, here's a testpage that shows the results of your proposed method vs. the Fisher-Yates method in your browser: http://phrogz.net/JS/JavaScript_Random_Array_Sort.html.

answered Dec 27, 2011 at 18:22
\$\endgroup\$
1
  • \$\begingroup\$ +1 on Fisher-Yates as a common and efficient algorithm for shuffling that is used in many places. You can read more about the algorithm en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle \$\endgroup\$ Commented Dec 27, 2011 at 21:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.