數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧
來源:懂視網
責編:小采
時間:2020-11-27 20:34:30
數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧
數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧:但是讓我感到意外的是,下面有個網友回復說,javascript中的Array本身的sort方法才是最快的,比快速排序算法都快,當時看到了很是郁悶,因為當時花了好長時間在排序算法上,居然忘記了Array本身的sort方法 不過javascript中內置的sort方法真的比快速排
導讀數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧:但是讓我感到意外的是,下面有個網友回復說,javascript中的Array本身的sort方法才是最快的,比快速排序算法都快,當時看到了很是郁悶,因為當時花了好長時間在排序算法上,居然忘記了Array本身的sort方法 不過javascript中內置的sort方法真的比快速排

但是讓我感到意外的是,下面有個網友回復說,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})
當然如果要排序的整數位數相同,不提供參數返回的結果也是一樣的,測試一下就知道:
代碼如下:
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com
數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧
數據排序誰最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧:但是讓我感到意外的是,下面有個網友回復說,javascript中的Array本身的sort方法才是最快的,比快速排序算法都快,當時看到了很是郁悶,因為當時花了好長時間在排序算法上,居然忘記了Array本身的sort方法 不過javascript中內置的sort方法真的比快速排