Skip to content

Instantly share code, notes, and snippets.

@monsterooo
Last active May 3, 2018 15:40
Show Gist options
  • Save monsterooo/bae186a5b59de92e7a67885dec317948 to your computer and use it in GitHub Desktop.
Save monsterooo/bae186a5b59de92e7a67885dec317948 to your computer and use it in GitHub Desktop.
洗牌算法

Fisher–Yates洗牌算法,它可是最优洗牌算法它不仅是无偏的,而且时间复杂度是O(n),空间复杂度是O(1),同时也非常容易实现,代码如下

function shuffle(array) {
  var n = array.length, t, i;
  while (n) {
    i = Math.random() * n-- | 0; // 0 ≤ i < n
    t = array[n];
    array[n] = array[i];
    array[i] = t;
  }
  return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment