您的位置:首页 > 编程语言 > Python开发

008 Python语法之冒泡排序-插入排序

2017-07-05 18:58 267 查看
简书地址:http://www.jianshu.com/p/c7a38899e715

普通冒泡排序(比较次数42)

list1 = [7, 1, 2, 3, 4, 5, 6]
length = len(list1)
for x in range(0, length - 1):
for y in range(0, length - 1):
if list1[y] > list1[y + 1]:
list1[y], list1[y + 1] = list1[y + 1], list1[y]
print(list1)


更新版冒泡排序(比较次数21)

list1 = [7, 1, 2, 3, 4, 5, 6]
for x in range(0, length - 1):
for y in range(0, length - 1 - x):
if list1[y] > list1[y + 1]:
list1[y], list1[y + 1] = list1[y + 1], list1[y]
print(list1)


究极版冒泡排序(比较次数11)

# 究极版冒泡排序
list1 = [7, 1, 2, 3, 4, 5, 6]
length = len(list1)
for i in range(0, length - 1):
bool = True
for j in range(0, length - 1 - i):
print(list1)
if list1[j] > list1[j + 1]:
list1[j], list1[j + 1] = list1[j + 1], list1[j]
bool = False
if bool:
break


插入排序

def insertSort(list1):
length = len(list1)
temp = 0
# 进行len - 1 次循环,每次循环都将下标为i的元素插入到它前面已经排好序的队列中
for i in range(1, length):
if list1[i] < list1[i - 1]:
temp = list1[i]
while i > 0 and temp < list1[i - 1]:
list1[i] = list1[i - 1]
i -= 1
list1[i] = temp

list1 = [7, 1, 2, 3, 4, 5, 6]
insertSort(list1)
print(list1)


模块引用

注意init文件需要有,定义module用的

import 文件夹名.文件夹名....py文件名


求三个数的最大值

第一版

def max(x, y, z):
max1 = x
if max1 < y:
max1 = y
if max1 < z:
max1 = z
return max1

print(max(1,2,3))


第二版

def max(x, y, z):
max1 = x
max1 = max1 if max1 > y else y
max1 = max1 if max1 > z else z
return max1

print(max(1,2,3))


总结

后面会出一篇介绍8大排序的文章,总结下排序的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python
相关文章推荐