当前位置:网站首页>JS数组方法 sort() 排序规则解析
JS数组方法 sort() 排序规则解析
2022-07-24 18:08:00 【无围之解】
我们用一个数组来测试sort()函数的排序方法,这里以升序为例。
打印参数 m、n 可以知道这个函数中究竟传入了什么值,借此就可以判断出来用的什么方法进行比较的:
var a = [3,1,5,4,8,9,32,19,6,21,77,64,15];
a.sort(function (m,n){
console.log( "m="+m+","+"n="+n )
return m-n;
})
console.log( a )
来看一下打印结果,
整个查找元素的过程,用到的方法其实就是折半查找,给大家画个图,带大家一探究竟:
这里我们先跳过前面7个元素的排序过程,因为整个比较过程所用到的方法是相同的。
我们发现:
首先会选择19前面的7个数字中,中间的那个数字(中间数字下标的计算方法:首尾下标的和的/2,将结果向上取整,例如3/2结果是1.5,向上取整得到的就是2),和其进行比较,
当大于这个数字时,就和其后面的元素再进行折半查找,
当小于这个数字时,就和其前面的元素进行折半查找,
直到找到一个位置,满足大于其前面的数字,小于其后面的数字。
小于首元素时,就将这个数字放数组的头部,大于尾元素时,就将这个数字放数组的尾部。
总结:JS的 sort() 排序,用到的是折半查找的方法。
注意,不能以 0 作为参考的分界线,也就是说,不是说 m - n > 0 就是降序,m - n < 0 就是升序,因为我们根本不能保证每次传入的两个参数谁大谁小。通过上面的图可以看到,m 表示新加入的要进行排序的元素,而 n 表示折半查找到的元素,这两者的大小关系不不是确定的。
边栏推荐
- Detailed explanation of ansible automatic operation and maintenance (V) the setting and use of variables in ansible, the use of jinja2 template and the encryption control of ansible
- 继承与派生
- Use prometheus+grafana to monitor MySQL performance indicators
- Wu Enda writes: how to establish projects to adapt to AI career
- 700. Search DFS method in binary search tree
- 1688/阿里巴巴按关键字搜索新品数据 API 使用说明
- How to follow the "low coupling" design principle?
- The solution of single chip microcomputer not supporting printf floating point type
- 213. 打家劫舍 II-动态规划
- pinia 入门及使用
猜你喜欢

Review and analysis of noodle dishes

Tensorflow introductory tutorial (37) -- DC Vnet

使用Prometheus+Grafana监控MySQL性能指标

C language custom type explanation - Consortium

05mysql lock analysis

PXE高效批量网络装机

Common methods of number and math classes

After separation, the impression notes are still difficult to live, but there are many coquettish operations

Icml2022 Best Paper Award: learning protein reverse folding from millions of predicted structures

安装JumpServer
随机推荐
ROC and AUC details of the recommended system
Laravel notes - RSA encryption of user login password (improve system security)
0627~ holiday knowledge summary
面会菜评论分析
[leetcode] 30. Concatenate substrings of all words
Alibaba /166 obtains the API instructions for all products in the store
05mysql lock analysis
Section 11 cache avalanche, hot data failure follow Daewoo redis ------- directory post
快速完成intelij idea的单元测试JUnit4设置
0612~quartz timer frame
分家后印象笔记过日子依然不好过,骚操作却不少
The ability to detect movement in vivo and build a safe and reliable payment level "face brushing" experience
Simple test JS code
头文件是必须的吗?跟一跟编译过程~~~
sklearn 的模型保存与加载使用
0630~ professional quality course
C语言自定义类型 — 枚举
JumpServer的使用
Get the original data API on 1688app
简单测试JS代码