当前位置:网站首页>js中数组排序的方法有哪些
js中数组排序的方法有哪些
2022-07-26 03:07:00 【二脸懵逼】
方法1:选择排序(简单选择排序)
选择排序是一种简单直观的排序算法,无论什么数据进去都是 O(n²) 的时间复杂度。所以用到它的时候,数据规模越小越好。唯一的好处可能就是不占用额外的内存空间了吧。
算法步骤:
- 首先在未排序序列中找到最小(大)元素,存放到排序序列的起始位置。
- 再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。
- 重复第二步,直到所有元素均排序完毕。
自述:①数组中的每一个元素和它后面的元素依次进行比较,第一轮找到的最大(最小)放在排序序列的起始位置;然后剩余的每一轮找到最大(最小)的数,将最大(最小的)元素放在已排序过的元素的后面。一个元素和后面的元素都比较完为一轮;重复以上步骤,直到完成。
代码示例:
let arr = [3, 57, 2, 8, 1,4];
for (let i = 0; i < arr.length-1; i++) {
//下标为i的元素和它之后的所有元素依次进行比较
for(let j=i+1;j<arr.length;j++){
//如果第一个比第二个大,就交换他们两个位置
if(arr[i]>arr[j]){
let temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
console.log('第'+(i + 1)+'轮的排序结果',arr);
}
console.log('选择排序完成后的数组:',arr);
运行结果:
动图演示:

方法2:冒泡排序
算法步骤:一次比较两个相邻的数,如果不符合规则互换位置,一次比较就能够将最大或最小的值放在数组最后一位, 继续对除最后一位之外的所有元素重复上述过程;
自述:
比较相邻的元素。如果第一个比第二个大,就交换他们两个。
对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。这步做完后,最后的元素会是最大的数。除了最后一个,针对所有的元素重复以上的步骤
持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。
代码示例:
let arr = [3, 57, 2, 8, 1, 4];
for (let i = 0; i < arr.length - 1; i++) {
//每一轮要比较多少次
for (let j = 0; j < arr.length - i - 1; j++) {
//如果第一个比第二个大,就交换他们两个位置
if (arr[j] > arr[j + 1]) {
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
console.log('第'+(i + 1)+'轮的排序结果',arr);
}
console.log('冒泡排序完成后的数组:', arr);
运行结果:

动图演示:

方法3:插入排序
算法步骤:
将数组第一个元素看做一个有序序列,把第二个元素到最后一个元素当成是未排序序列。
从头到尾依次扫描未排序序列,将扫描到的每个元素插入有序序列的适当位置。
如果待插入的元素与有序序列中的某个元素相等,则将待插入元素插入到相等元素的后面。
代码示例:
//插入排序
let arr = [3, 57, 2, 8, 1, 4];
for (let i = 1; i < arr.length; i++) {
let prevIndex = i - 1;//正在比较元素的前一个元素的下标(初始值)
let current = arr[i];//需要和前面进行比较的元素
// 当需要排序比较的元素的前一个元素比需要排序比较的元素大时
while (prevIndex >= 0 && arr[prevIndex] > current) {
arr[prevIndex + 1] = arr[prevIndex];
//比较完后,继续和前面一个的元素比较,直至不满足条件
prevIndex--;
}
arr[prevIndex + 1] = current;
console.log('第'+(i)+'轮的排序结果',arr);
}
console.log('插入排序完成后的数组:', arr);
运行结果:

动图演示:

方法4:快速排序(依托递归函数)
算法步骤:
- 从数列中挑出一个元素,称为 “基准”(pivot);
- 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作;
- 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序
代码示例:
//快速排序
let arr = [3, 57, 2, 8, 1, 4];
//创建快速排序函数
function quickSort(tempArr) {
//递归终止条件
if (tempArr.length <= 1) {
return tempArr;
}
//取基准
let pivotIndex = Math.floor(tempArr.length / 2);
//将获取到的基准的下标从元素组中删除并赋值给pivot
let pivot = tempArr.splice(pivotIndex, 1);
//分左右
let leftArr = [];
let rightArr = [];
for (let i = 0; i < tempArr.length; i++) {
if (tempArr[i] > pivot) {
//满足条件的元素添加进rightArr这个数组
rightArr.push(tempArr[i]);
} else {
leftArr.push(tempArr[i]);
}
}
return quickSort(leftArr).concat(pivot, quickSort(rightArr));
}
console.log('快速排序后的数组',quickSort(arr));
运行结果:

动图演示:

方法5:js中提供的sort()方法
sort()方法是数组自带的一种排序方法,默认情况下会将元素按照字符串进行比较。
基本思想:
根据提供的排序规则,对数组元素进行排序。
使用数字排序,必须通过一个函数作为参数来调用。
代码示例:
//升序
function fun1(a, b) {
return a - b;
}
//降序
function fun2(a, b) {
return b - a;
}
console.log([3, 57, 2, 8, 1, 4].sort(fun1));
console.log([3, 57, 2, 8, 1, 4].sort(fun2));
运行结果:
边栏推荐
- Programming example of STM32 state machine -- fully automatic washing machine (Part 1)
- STM - exti external interrupt learning notes
- [NOIP2001 普及组]装箱问题
- MySQL tutorial: MySQL database learning classic (from getting started to mastering)
- Software testing post: Ali has three sides. Fortunately, he has made full preparations and has been offered
- How to effectively prevent others from wearing the homepage snapshot of the website
- 文件操作(一)——文件简介与文件的打开方式和关闭
- How to reinstall win7 system?
- Type the URL to the web page display. What happened during this period?
- Pbootcms upload thumbnail size automatically reduces and blurs
猜你喜欢

The LAAS protocol elephant of defi 2.0 is the key to revitalizing the development of defi track

【尤里复裂人】带你轻松理解——深拷贝和浅拷贝
![[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)](/img/b8/56c4541602c5a6e787e2455f80febd.png)
[steering wheel] use the 60 + shortcut keys of idea to share with you, in order to improve efficiency (live template & postfix completion)

这种动态规划你见过吗——状态机动态规划之股票问题(上)

【C进阶】深入探索数据的存储(深度剖析+典例解读)

Digital commerce cloud DMS dealer management system solution: DMS system realizes business Omni channel and sales data collection

Opencv 在图像上进行标注(画框+写字)

MySQL教程:MySQL数据库学习宝典(从入门到精通)

Self-supervised learning method to solve the inverse problem of Fokker-Planck Equation

VR panoramic shooting and production of business center helps businesses effectively attract people
随机推荐
Opencv报错:(parameter or structure field))Unrecognized or unsupported array type in functon ‘cvGetMat‘
Longest Substring Without Repeating Characters
Three years of software testing experience, salary has been stuck at 10K, how to improve and develop automated testing?
ES6 set and map
Win11隐藏输入法状态栏方法
[SQL] CASE表达式
Autojs cloud control source code + display
Opencv 以指定格式保存图片
Extended Physics-InformedNeural Networks论文详解
dataframe整理:datetime格式分拆;删除特定行;分组整合。
多线程编程
c语言分层理解(c语言函数)
JSD-2204-酷鲨商城(管理商品模块)-Day02
微信公众号互助、开白群,小白报团取暖
Anti electronic ink screen st7302
Software testing post: Ali has three sides. Fortunately, he has made full preparations and has been offered
LeetCode·每日一题·919.完全二叉树插入器·层次遍历·BFS
Continuous delivery and Devops are good friends
Zhimeng prompts you how to solve the problem of setting the field as linkage type
Swin Transformer【Backbone】