我做了一些研究关于JavaScript的排序算法的性能比较,发现意想不到的效果.冒泡排序提供了比其他更好的性能,如Shell排序,快速排序和本机Javascript功能.为什么会这样?也许我的性能测试方法错了?
你可以在这里找到我的研究结果.
以下是一些算法实现示例:
/**
* 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; …Run Code Online (Sandbox Code Playgroud)