当前位置:网站首页>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 表示折半查找到的元素,这两者的大小关系不不是确定的。
边栏推荐
- 阿里巴巴1688按关键字搜索商品 API 使用展示
- In depth analysis of the famous Alibaba cloud log4j vulnerability
- Definition and storage of adjacency table and adjacency storage of directed graph and undirected graph
- Pay close attention! List of the latest agenda of 2022 open atom open source Summit
- 0630~ professional quality course
- 还在用命令行看日志?快用Kibana吧,可视化日志分析YYDS!
- Review and analysis of noodle dishes
- 05mysql lock analysis
- 面会菜评论分析
- 1688/阿里巴巴按关键字搜索新品数据 API 使用说明
猜你喜欢

邻接表的定义和存储以及有向图无向图的邻接存储

C language custom types - Enumeration

Dry goods | three sub domain name collection tools worth collecting
![[OBS] dependency Library: x264 vs Build](/img/24/4caea5dc6ff092a3161f43b6026d25.png)
[OBS] dependency Library: x264 vs Build

Gan Development Series II (pggan, Singan)

Shanghai Jiaotong University team used joint deep learning to optimize metabonomics research

Section 7 Data Dictionary: hash followed by Daewoo redis ------- directory post

手写博客平台~第二天

Flink operation Hudi data table

安装JumpServer
随机推荐
Blackmagic Fusion Studio 18
仅需一个依赖给Swagger换上新皮肤,既简单又炫酷!
C语言中的字符与字符串库函数的使用以及模拟实现
Alibaba /1688 API instructions for searching products by map (pailitao)
The ability to detect movement in vivo and build a safe and reliable payment level "face brushing" experience
0627~放假知识总结
《STL源码剖析》应该怎样读?
Still reading logs on the command line? Use kibana, visual log analysis yyds!
Opencv picture rotation
阿里巴巴/1688按图搜索商品(拍立淘) API使用说明
Simple test JS code
Quickly complete the unit test junit4 setting of intelij idea
213. Looting II - Dynamic Planning
C language custom types - Enumeration
如何向 google colab 快速上传文件
Win10 super good-looking mouse theme, you also try it
Get the original data API on 1688app
【obs】依赖库: x264 vs 构建
分家后印象笔记过日子依然不好过,骚操作却不少
Learn redisson from scratch ------- topics (subscription and distribution)