Algorithms and Data Structures · Senior · Question 18 of 75
What is wrong with shuffling an array via arr.sort(() => Math.random() - 0.5)?
- 1It throws because the comparator isn't consistent
- 2It always returns the array in its original order
- ✓Correct answer: The result is biased; Fisher-Yates is uniform
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.