当前位置:网站首页>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]
边栏推荐
猜你喜欢
随机推荐
EndNoteX9 OR X 20 指南
【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
记录一次被入侵5900端口经历
6. The File types
Ontology development diary 02 - simple sparql query
关于一次性通过CISSP考试的一点经验分享
mac 上安装Redis和配置
A little experience sharing about passing the CISSP exam at one time
2021-04-26QGIS3.10加载天地图影像(地图瓦片)的一种方法
Tigase插件编写——注册用户批量查询
实验室装修及改造工程程序简介
LeetCode147:对链表进行插入排序 画图分析 思路清晰!
MySQL约束关系,你必须要知道的知识点!
2.线程创建
JDBC中的增删改查操作
8. Recursively traverse and delete cases
Go-控制语句那些事
8.Properties property collection
Dream Notes 0809
LeetCode179:最大数(C语言)代码简洁!