当前位置:Gxlcms > JavaScript > 数据排序谁最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧

数据排序谁最快(javascript中的Array.prototype.sortPK快速排序)_javascript技巧

时间:2021-07-01 10:21:17 帮助过:6人阅读

但是让我感到意外的是,下面有个网友回复说,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})

当然如果要排序的整数位数相同,不提供参数返回的结果也是一样的,测试一下就知道:
代码如下: