当排序函数运行时,每x秒向要排序的数组添加新的随机数例如x可以是1秒。100k随机数数组的排序大约需要10秒排序函数如何更新以考虑在函数运行时插入的新随机数?如有必要,可以使用web工作者来模拟并发性。
https://repl.it/repls/OutstandingVioletPolyhedron
let a;
for (a=[],i=0;i<100000;++i)
a[i]=i;
function shuffle(array) {
let tmp, current, top = array.length;
if(top) while(--top) {
current = Math.floor(Math.random() * (top + 1));
tmp = array[current];
array[current] = array[top];
array[top] = tmp;
}
return array;
}
a = shuffle(a)
const insertionSort = arr => {
const len = arr.length;
for (let i = 0; i < len; i++) {
let el = arr[i];
let j;
for (j = i - 1; j >= 0 && arr[j] > el; j--) {
arr[j + 1] = arr[j];
}
arr[j + 1] = el;
}
console.log(arr)
return arr;
};
const start = performance.now()
a = insertionSort(a)
const end = performance.now()
const time = (end - start) / 1000
console.log("time", time)
最佳答案
Javascript是单线程的它一次只能做一件事。要使此工作正常,您必须以非占有的方式重写排序函数,以便它在一段特定时间后将控制权传递回其他操作。
关于javascript - 在排序时在数组中插入新的随机数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58286608/