//工具函数:交换两个值 Array.prototype.swap = function (i, j) { var t = this[i]; this[i] = this[j]; this[j] = t; }; Array.prototype.quickSort = function () { this.quickSortHelper(0, this.length-1); }; Array.prototype.quickSortHelper = function(start,end){ if(start>=end){ return; } var pivot = this[start]; var pivotIdx = start; var i = start+1; var n = end; while(i<=n){ if(this[i] < pivot){ this.swap(pivotIdx,i); i++; pivotIdx = i; }else{ this.swap(n,i); n--; } } this.quickSortHelper(start,pivotIdx-1); this.quickSortHelper(pivotIdx+1,end); }
测试一下快速排序的性能
// test function test () { var arr = []; for (var i = 0; i < 1000000; i++) { arr.push(Math.round(Math.random(i) * 10000)); } doTest(arr, 1); } function doTest(arr, n) { var tStart = (new Date()).getTime(); var re = arr.quickSort(); var tEnd = (new Date()).getTime(); console.log('快速排序使用时间是:' + (tEnd - tStart) + 'ms'); return re; } test();//输出:快速排序使用时间是:215ms