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

简书地址: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)

模块引用

  1. 注意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大排序的文章,总结下排序的使用。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值