当前位置:网站首页>排序1:冒泡排序
排序1:冒泡排序
2022-08-09 09:45:00 【用户9955628】
思路:依次比较相邻两个元素,小的排在前面,大的排在后面,发现顺序错误就交换两者的前后顺序。
range函数:
range(start,stop,[step]):生成一个可迭代对象
注意点:
setp可以省略,默认为1
左闭右开区间
举例:
range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
range(0)
[]
range(1, 0)
[]
python3实现:
from typing import List
def bubble_sort(arr: List[int]):
"""
arr:待排序列表,list中的元素类型为int
"""
length = len(arr)
#列表长度为1和0时直接返回
if length <= 1:
return
for i in range(length-1):
is_made_swap = False
#设置标志位,如果已经有序,则直接跳出
for j in range(length-1):
if arr[j] > arr[j+1]:
arr[j],arr[j+1] = arr[j+1],arr[j]
is_made_swap = True
if not is_made_swap:
break
if __name__ == '__main__':
import random
random.seed(54)
arr = [random.randint(0,100) for _ in range(10)]
print("原始数据", arr)
bubble_sort(arr)
print("排序后:",arr)
结果:
原始数据 [17, 56, 71, 38, 61, 62, 48, 28, 57, 42]
排序后: [17, 28, 38, 42, 48, 56, 57, 61, 62, 71]边栏推荐
- 程序环境和预处理
- Ontology Development Diary 05-Strive to Understand SWRL (Part 2)
- Rights management model, ACL, RBAC and ABAC (steps)
- 3. Coding method
- 日期操作比较全面得代码
- LPP代码及其注释
- OSCS开源软件安全周报,一分钟了解本周开源软件安全大事
- Quick sort eight sorts (3) 】 【 (dynamic figure deduction Hoare, digging holes, front and rear pointer method)
- 3.编码方式
- 6. The File types
猜你喜欢

EndNote使用指南

try catch 对性能影响

多线程(基础)

Quick sort eight sorts (3) 】 【 (dynamic figure deduction Hoare, digging holes, front and rear pointer method)

有返回值的函数

BigDecimal用法常用操作记录
Redis 回击 Dragonfly:13 年后,Redis 的架构依然是同类最佳

安装torch_sparse失败解决方法
![[Machine Learning] Detailed explanation of web crawler combat](/img/ac/f00f0c81e66ba526ac39ee60fad72b.png)
[Machine Learning] Detailed explanation of web crawler combat

LeetCode147:对链表进行插入排序 画图分析 思路清晰!
随机推荐
8.递归遍历和删除案例
Anti App so层对抗分析
命令行查询数据库
程序环境和预处理
拿下跨界C1轮投资,本土Tier 1高阶智能驾驶系统迅速“出圈”
Redis 回击 Dragonfly:13 年后,Redis 的架构依然是同类最佳
秒拍app分析
MySQL常用存储引擎,你不可错过的知识点!
多线程案例——阻塞式队列
文件操作
Ontology development diary 02 - simple sparql query
Ontology development diary 04 - to try to understand some aspects of protege
多线程案例——定时器
免费下载天地图全国基础地理信息矢量数据的一种方法
列表
vgg网络结构
慕课网-简易扑克牌游戏 思路清晰 简易版
LeetCode(剑指 Offer)- 25. 合并两个排序的链表
《刷题日记》2
缓存击穿,缓存穿透,缓存雪崩的解释和对应的一些解决方案