当前位置:网站首页>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 表示折半查找到的元素,这两者的大小关系不不是确定的。
边栏推荐
- [network security] analysis vulnerability of website Middleware
- Int8 & int8, have you ever stumbled like this?
- 《STL源码剖析》应该怎样读?
- File upload vulnerability -.User.ini and.Htaccess
- [leetcode] 30. Concatenate substrings of all words
- 还在用命令行看日志?快用Kibana吧,可视化日志分析YYDS!
- C语言中的字符与字符串库函数的使用以及模拟实现
- 1688/ Alibaba searches new product data by keyword API instructions
- Get the data of Tongcheng (elong) Hotel
- 阿里巴巴/1688按图搜索商品(拍立淘) API使用说明
猜你喜欢

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

6126. 设计食物评分系统

T245982 "kdoi-01" drunken flower Yin

Definition and storage of adjacency table and adjacency storage of directed graph and undirected graph

Use prometheus+grafana to monitor MySQL performance indicators

Use of jumpserver

05mysql lock analysis
![[network security] analysis vulnerability of website Middleware](/img/3a/9c034c17d65348aa7c35a3dac2039c.png)
[network security] analysis vulnerability of website Middleware

ShardingSphere数据库读写分离

C language to achieve a static version of the address book
随机推荐
213. 打家劫舍 II-动态规划
SSM framework learning
File upload vulnerability -.User.ini and.Htaccess
获取1688app上原数据 API
Definition and storage of adjacency table and adjacency storage of directed graph and undirected graph
单细胞代码解析-妇科癌症单细胞转录组及染色质可及性分析1
0615~用自定义注解实现RBAC权限管理
mac数据库管理软件Navicat Premium Essentials Mac
0621~ES&Lucene
Polymorphism, abstract class, interface
Simple test JS code
700. Search DFS method in binary search tree
0621~ES&Lucene
Model saving and loading of sklearn
Awk from getting started to getting into the ground (19) awk extensions make awk even stronger
Inherit, override, overload
0627~放假知识总结
Alibaba /1688 API instructions for searching products by map (pailitao)
redis集群的三种方式
Review and analysis of noodle dishes