Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
301 views
in Technique[技术] by (71.8m points)

这样的排序方法有毛病吗?

// 打乱数组
function shuffle(data){
    let startIndex = 0,
        endIndex = length = data.length - 1;
    while(endIndex){
        let index = Math.floor(Math.random()*length);
        [data[index], data[endIndex]] = [data[endIndex], data[index]];
        endIndex--;
    }
}

// 具有负数或重复值的数据除外,使用这种方式似乎比其他排序更快一些。
var obj = {};
var arr = Array.from({length:1e5},(item,index)=>index);

shuffle(arr);
console.time();
arr.forEach(item => { obj[item] = item });
console.log(Object.values(obj));
console.timeEnd();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

没什么毛病,就是洗牌算法,不过洗牌算法乘以length会有重复的洗牌过程,所以可以直接

let index = Math.floor(Math.random()*endIndex);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...