当前位置:网站首页>1: bubble sort
1: bubble sort
2022-08-09 09:59:00 【User 9955628】
Idea: Compare two adjacent elements in turn, the smaller ones are in the front, the larger ones are in the back, and if the order is wrong, the order of the two is swapped.
range function:
range(start,stop,[step]): Generate aiterate objectbe careful:setp can be omitted, the default is 1Left closed right open intervalExample:range(10) # start from 0 to 10[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]range(0, 30, 5) # steps are 5[0, 5, 10, 15, 20, 25]range(0, 10, 3) # steps are 3[0, 3, 6, 9]range(0, -10, -1) # negative numbers[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]range(0)[]range(1, 0)[]
python3 implementation:
from typing import Listdef bubble_sort(arr: List[int]):"""arr: the list to be sorted, the element type in the list is int"""length = len(arr)#Return directly when the list length is 1 and 0if length <= 1:returnfor i in range(length-1):is_made_swap = False#Set the flag bit, if it is already in order, jump out directlyfor j in range(length-1):if arr[j] > arr[j+1]:arr[j],arr[j+1] = arr[j+1],arr[j]is_made_swap = Trueif not is_made_swap:breakif __name__ == '__main__':import randomrandom.seed(54)arr = [random.randint(0,100) for _ in range(10)]print("raw data", arr)bubble_sort(arr)print("After sorting: ",arr)result:Raw data [17, 56, 71, 38, 61, 62, 48, 28, 57, 42]After sorting: [17, 28, 38, 42, 48, 56, 57, 61, 62, 71]
边栏推荐
- OSCS开源软件安全周报,一分钟了解本周开源软件安全大事
- 缓存击穿,缓存穿透,缓存雪崩的解释和对应的一些解决方案
- 搭建Tigase进行二次开发
- 多线程案例——阻塞式队列
- m个样本的梯度下降
- 批量修改Shapefile属性表的一种方法(使用gdal.jar)
- Practical skills: a key for image information in the Harbor, quick query image
- 【ASM】字节码操作 MethodVisitor 案例实战 生成对象
- 五个不同事物隔离级别,七个事物传播行为
- Ontology Development Diary 03 - When debugging is in progress
猜你喜欢
随机推荐
Tom Morgan | Twenty-One Rules of Life
4.泛型和工具类
[ASM] Bytecode operation MethodVisitor case combat generation object
Celebrate ranked 18
ORA-00600 [16703], [1403], [20]问题分析及恢复
实用小技能:一键获取Harbor中镜像信息,快捷查询镜像
Secretive present: in modern times
主从postition变化无法锁定_Slave_IO_Running显示No_Slave_Sql_Running显示No---Mysql主从复制同步002
EndNote User Guide
OSCS开源软件安全周报,一分钟了解本周开源软件安全大事
STM32F103实现IAP在线升级应用程序
【ASM】字节码操作 MethodVisitor 案例实战 生成对象
Redis 缓存主动更新策略
6.File类
3.编码方式
时间复杂度和空间复杂度
2.Collection interface
3.List interface and implementation class
循环嵌套以及列表的基本操作
EndNoteX9 OR X 20 Guide