数组随机排序的算法

今天被问到了一个随机排序的算法,然后去网上查了一下资料 整理如下

数组随机排序其基本原理是洗牌算法(Fisher–Yates shuffle):
是一种将有限集合的顺序打乱的一种算法
1.使用sort排序

var arr = [1,2,3,4,5,6,7,8,9];
arr.sort(function(a, b) {
    return Math.random() > 0.5 ? -1 : 1;
});

   

  2.递归的方法

function randomSort(arr, newArr) {
    if( arr.length == 1 ) {
        newArr.push(arr[0])
        // 相当于递归退出
        return newArr;
    }
    // 在原数组length基础上取出一个随机数
    var random = Math.ceil(Math.random()*arr.length) - 1;
    // 将原数组中的随机一个值push到新数组newArr中
    newArr.push(arr[random]);
    // 对应删除原数组arr的对应数组项
    arr.splice(random, 1);
    return randomSort(arr, newArr);
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var newArr = [];
randomSort(arr, newArr);
console.log(newArr);

  

3.随机交换数组内的元素

var range = function(min, max) {
    return min + Math.floor(Math.random()*(max - min + 1));
}
Array.prototype.shuffle = function(n) {
        var len = this.length,
                num = n ? Math.min(n, len) : len,
                arr = this.slice(0),
                temp,
                index;
        for( var i = 0; i < len; i++ ) {
            //返回一个随机值
            index = range(i, len - 1);
            //储存当前的值
            temp = arr[i];
            //把随机的值和当前的值替换
            arr[i] = arr[index];
            //把当前的值替换成缓存的值
            arr[index] = temp;
        }
        //返回一个新数组而不是副本
        return arr.slice(0, num);
};

4.underscore.js 中的 shuffle 方法

function random(min, max) {
    if (max == null) {
      max = min;
      min = 0;
    }
    return min + Math.floor(Math.random() * (max - min + 1));
};
function shuffle(arr) {
  var length = arr.length,
      shuffled = Array(length);
  for (var index = 0, rand; index < length; index++) {
      rand = random(0, index);
      if (rand !== index) shuffled[index] = shuffled[rand];
      shuffled[rand] = arr[index];
    }
    return shuffled;
}

  

这篇文章主要总结和收集了有关于数组随机排序一些算法 :)

原文地址:https://www.cnblogs.com/web-alibaba/p/5294982.html