当前位置:网站首页>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]
边栏推荐
猜你喜欢
Win系统 - 罗技 G604 鼠标蓝灯闪烁、失灵解决方案
Quick sort eight sorts (3) 】 【 (dynamic figure deduction Hoare, digging holes, front and rear pointer method)
拿下跨界C1轮投资,本土Tier 1高阶智能驾驶系统迅速“出圈”
【八大排序①】插入排序(直接插入排序、希尔排序)
程序环境和预处理
【个人学习总结】CRC校验原理及实现
try catch 对性能影响
LeetCode148:排序链表 归并排序,思路清晰,C语言练习看过来!
Arrays类、冒泡排序、选择排序、插入排序、稀疏数组!
electron 应用开发优秀实践
随机推荐
Ontology development diary 04 - to try to understand some aspects of protege
EndNoteX9 OR X 20 Guide
7.FileFilter interface
【size_t是无符号整数 (-1 > 10) -> 1】
mac 上安装Redis和配置
Dream Notes 0809
6.File类
2. Thread creation
安装torch_sparse失败解决方法
Browser error classification
Multi-threaded cases - timer
Redis 回击 Dragonfly:13 年后,Redis 的架构依然是同类最佳
【个人学习总结】CRC校验原理及实现
5. Transform Streams
2021-04-26QGIS3.10加载天地图影像(地图瓦片)的一种方法
慕课网-简易扑克牌游戏 思路清晰 简易版
3.List interface and implementation class
在anaconda环境中配置cuda和cudnn
8.递归遍历和删除案例
日期操作比较全面得代码