但是讓我感到意外的是,下面有個網友回復說,javascript中的Array本身的sort方法才是最快的,比快速排序算法都快,當時看到了很是郁悶,因為當時花了好長時間在排序算法上,居然忘記了Array本身的sort方法
不過javascript中內置的sort方法真的比快速排序算法還快嗎?
哈哈,測試一下不就知道了
先說一下我測試的環境
1,我的測試環境是IE6.0和firefox2.0
2,每種算法有很多種不同的實現方法,下面測試中我選擇上面網友實現的快速排序算法,只是把內嵌函數搬到了外面
3,算法執行的速度與數據的類型、大小、數據量的多少都有關系,我這里只比較 小于 999999 的整數的排序,數據量分別定為500、2000、30000
關于sort方法:sort方法是Array的一個內置的方法:javascript權威指南 中是這樣定義的:
The sort( ) method sorts the elements of array in place: no copy of the array is made. If sort( ) is called with no arguments, the elements of the array are arranged in alphabetical order (more precisely, the order determined by the character encoding). To do this, elements are first converted to strings, if necessary, so that they can be compared.
If you want to sort the array elements in some other order, you must supply a comparison function that compares two values and returns a number indicating their relative order. The comparison function should take two arguments, a and b, and should return one of the following:
sort方法可以接受一個function類型的參數來自定義自己的排序邏輯,當沒有提供參數的時候,默認按照字符順序排序,所以對整數排序需要提供一個function類型的參數,本測試的調用方式如下:
array.sort(function(a,b){return a-b})
當然如果要排序的整數位數相同,不提供參數返回的結果也是一樣的,測試一下就知道:
代碼如下:
<script>
alert( [3,4,5,11,1].sort())
alert([3,4,5,11,1].sort(function(a,b){return a-b}))
</script>
提示:可以先修改了再運行
得到的結果是 [1, 11, 3, 4, 5],顯然不是我們要的結果
生成需要排序的數組,為了得到公正的結果我先隨機生成用于排序的數組,每次比較中兩種方法使用的數組都具有相同的元素,下面是生成隨機數組的代碼
代碼如下:
function random(m,n){
//生成一個m、n之間的整數
var i=Math.random();
return Math.round((n-m)*i+m);
}
function getRandomArr(m,n,l){
//m:生成隨即整數的最小值,n:生成隨即整數的最大值,l:生成的數組的長度
var resultArr=[];
for(var i=0;i<l;i++){
resultArr.push(random(m,n))
}
return resultArr;
}
快速排序算法的實現,這個算法取自我看到的51js論壇上這個網友的實現,代碼如下:
代碼如下:
function doSort(a,s,e)
{
新聞熱點
疑難解答