当前位置:网站首页>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]边栏推荐
- [ASM] Bytecode operation MethodVisitor case combat generation object
- 通过程序发送 Gmail 邮件
- 2.Collection interface
- MySQ事务控制语言-TCL,进来学习!
- cannot import name ‘load_offloaded_weights‘ from ‘accelerate.utils‘ (/home/huhao/anaconda3/envs/huha
- 如何快速打通镜像发布流程?
- 拿下跨界C1轮投资,本土Tier 1高阶智能驾驶系统迅速“出圈”
- A Practical Guide to Building OWL Ontologies using Protege4 and CO-ODE Tools - Version 1.3 (7.4 Annotation Properties - Annotation Properties)
- 【ASM】字节码操作 MethodVisitor 案例实战 生成对象
- 【机器学习】数据科学基础——机器学习基础实践(二)
猜你喜欢
随机推荐
从源码分析UUID类的常用方法
m个样本的梯度下降
.equals==
Ontology development diary 04 - to try to understand some aspects of protege
6.File类
LeetCode179:最大数(C语言)代码简洁!
ArrayList和LinkedList
pycharm在创建py文件时如何自动注释
需求侧电力负荷预测(Matlab代码实现)
Tom Morgan | Twenty-One Rules of Life
Go-指针的那些事
[Machine Learning] Detailed explanation of web crawler combat
【八大排序④】归并排序、不基于比较的排序(计数排序、基数排序、桶排序)
Sweet alert
Thread,Runnable,ExecutorService线程池控制下线程量
Command line query database
8.Properties property collection
Cisco common basic configuration of common commands
五个不同事物隔离级别,七个事物传播行为
Go-控制语句那些事









