JavaScript性能中的快速排序


function qsort(a) {
if (a.length == 0) return [];
var left = [], right = [], pivot = a[0];
for (var i = 1; i < a.length; i++) {
a[i] < pivot ? left.push(a[i]) : right.push(a[i]);
}
return qsort(left).concat(pivot, qsort(right));
}

为什么上面的QuickSort算法比原生 array.sort(( 方法得多?

var array = Array.from({
length: 100000
}, () => Math.floor(Math.random() * 100));

array.slice(0).sort((a,b) => a-b); // 34ms

qsort(array) // 2436ms

好吧,本机方法不会在javascript中以递归方式创建和改变数组。

最新更新