Algorithms and Data Structures · Senior · Question 18 of 75

What is wrong with shuffling an array via arr.sort(() => Math.random() - 0.5)?

Explanation

Sort algorithms assume a consistent comparator; random answers make some permutations much more likely, depending on the engine. Fisher-Yates swaps each position with a random earlier one in O(n) and is uniform.

Further reading

Problem with a question

Algorithms and Data Structures · Senior · question 18

Test yourself

Take the Algorithms and Data Structures · Senior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz