8
我已经做了一些关于使用Javascript排序算法性能比较的research,并且发现了意想不到的结果。泡泡排序提供比其他更好的性能,例如Shell排序,快速排序和本地Javascript功能。为什么会发生?也许我在我的性能测试方法中错了?为什么Javascript的Bubble排序比其他排序算法快得多?
您可以查看我的研究结果here。
这里有一些算法实现的例子:
/**
* Bubble sort(optimized)
*/
Array.prototype.bubbleSort = function()
{
var n = this.length;
do {
var swapped = false;
for (var i = 1; i < n; i++) {
if (this[i - 1] > this[i]) {
var tmp = this[i-1];
this[i-1] = this[i];
this[i] = tmp;
swapped = true;
}
}
} while (swapped);
}
/**
* Quick sort
*/
Array.prototype.quickSort = function()
{
if (this.length <= 1)
return this;
var pivot = this[Math.round(this.length/2)];
return this.filter(function (x) { return x < pivot }).quickSort().concat(
this.filter(function (x) { return x == pivot })).concat(
this.filter(function (x) { return x > pivot }).quickSort());
}
我认为调用'filter',其他'quickSort'和'concat'使得quickSort非常慢。 – JiminP