Skip to content

Instantly share code, notes, and snippets.

@JSoon
Created April 16, 2018 02:50
Show Gist options
  • Save JSoon/010b721bb0ee79b52685944695d75b38 to your computer and use it in GitHub Desktop.
Save JSoon/010b721bb0ee79b52685944695d75b38 to your computer and use it in GitHub Desktop.
Fisher–Yates 随机排序算法
/**
* Fisher–Yates shuffle
*
* https://blog.oldj.net/2017/01/23/shuffle-an-array-in-javascript/
* https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
* https://github.com/lodash/lodash/blob/b0980a90fc83bc92e040f905ebed8196f895949c/.internal/shuffleSelf.js
* @param {array} array
*/
var shuffle = function (array) {
var counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
var index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
var temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment