当前位置:网站首页>JS中的冒泡排序
JS中的冒泡排序
2022-07-27 15:55:00 【夏诗曼CharmaineXia】
var arr = [2,1,3];
在C#中的冒泡排序:
for(var i=0;i<arr.length -1 ;i++){
for(var j=0;j<arr.length -1 -i;j++){
if(arr[j] - arr[j+1] > 0){
var t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
在JavaScript中的冒泡排序:
arr.sort(function(a,b) {return b-a});
是怎么演变过来的,步骤如下:
- 把if(arr[j] - arr[j+1] > 0)抽象成如下
if(f(arr[j] , arr[j+1]) > 0){}
- 在整个冒泡排序外面套上一个函数名,使其变为函数体
//arr:数组
//f:函数
var mySort = function(arr,f){
//不给f传值,默认为升序排列
//f=f ? f:function(a,b) {return a-b;};
//下面是三元表达式的简写
f=f || function(a,b) {return a-b;};
for(var i=0;i<arr.length -1 ;i++){
for(var j=0;j<arr.length -1 -i;j++){
if(f(arr[j] , arr[j+1]) > 0){
var t = arr[j];
arr[j] = arr[j+1];
arr[j+1] = t;
}
}
}
}
- 使用这个函数
mySort(arr,f);
alert(arr);
f代表一个函数,因此写成如下样式
//b-a可以实现降序排序
mySort(arr,function(a,b) {return b-a});
alert(arr);
边栏推荐
- 卷积神经网络之卷积计算过程个人理解
- 【Codeforces】 B. Make it Divisible by 25
- Activate genuine win7 ultimate system with slmgr command
- Mysql database defines cursor in trigger
- 机器学习——概念理解之IoU
- Zhengzhou University database course resource description
- In the fourth week of July, Yidun business risk control focused on the supreme law to regulate app's forcible request for personal information
- Summer Challenge [FFH] real time chat room websocket practice
- 查找表中多余重复记录并删除保留最小一个
- shell常见命令(1)——变量大小写转换
猜你喜欢

Convolutional neural network -- Translation of yolov1 thesis

An end-to-end file upload program based on form, including client and server

How to learn C language? This article gives you the complete answer

初识多态

微信小程序 云函数批量删除多条数据 Error: errCode: -502005 database collection not exists

C语言怎么学?这篇文章给你完整答案

JSP自定义标签(下)
What are the safety risks of small games?

Likeshop takeout ordering system "100% open source without encryption"

卷积神经网络——FPN(Feature Pyramid Networks)介绍
随机推荐
快解析结合华途文档加密软件
笔试缺考者入围教师招聘面试?河南祥符:个别考生成绩统计错误
2022 safety officer-a certificate examination questions and online simulation examination
[MCU] 2.2 pin function of AT89S52
机器学习之评价指标(一)——回归评价指标
Activate genuine win7 ultimate system with slmgr command
Zhengzhou University database course resource description
C语言怎么学?这篇文章给你完整答案
【Codeforces】 B. Make it Divisible by 25
Oracle 11g database installation tutorial
How to learn C language? This article gives you the complete answer
机器学习——概念理解之IoU
Likeshop takeout ordering system "100% open source without encryption"
Wechat applet to make calls
mysql解决唯一索引重复导致的插入失败问题
Interviewer: what is scaffolding? Why do you need scaffolding? What are the commonly used scaffolds?
ACL 2022 | prompt based automatic depolarization: effectively reducing bias in the pre training language model
Layout of flutter
Some suggestions for writing original technical articles
Detailed explanation of browser caching mechanism