Closed mcorrell closed 8 years ago
For my own code I prefer incrementing for loops over decrementing while loops. Both are O(n). The decrementing version I think will be slightly faster in practice (the space of possible swaps gets smaller and smaller with each decrement, for instance). The decrementing version is also technically more accurate, since the incrementing version allows multiple swaps of the same value (which means the identity permutation is slightly less likely, among other properties).
Switching over is certainly easy enough.
I don't care about the performance difference but found the decrementing version to be more understandable.
More importantly, why do you create a copy when the explicit advantage of the algorithm is that you can shuffle in place? If it is explicit (e.g. no return value), users can make a copy themselves if they need to.
Also personal preference: I prefer these methods to not have side effects.
But precedent both externally (for instance php's std shuffle()
method) and internally (most of the other array methods in util have side effects) backs you up, so I'll switch over.
LGTM. I changed the tests a bit but this looks good to go.
Permutes an array in place. Permuted with a Knuth shuffle aka the Fisher-Yates shuffle.