python实现冒泡排序和插入排序

alist = [5, 1, 5, 2, 6,9, 0, 7, ]

# 冒泡插入两者其实差不多

# 插入排序
# 从小到大: 每一次拿当前元素和前一个元素对比,如果小就交换位置,否则结束内层循环
def inser_sort(alist):
    for i in range(1, len(alist)):
        for j in range(i, 0, -1):
            if alist[j] < alist[j - 1]:
                alist[j], alist[j - 1] = alist[j - 1], alist[j]
            else:
                break
    return alist

# 冒泡排序(每一次把前面符合条件的冒泡到最后)
def func(alist):
    for i in range(len(alist)):
        for j in range(0, len(alist) - 1 - i):
            if alist[j + 1] < alist[j]:
                alist[j + 1], alist[j] = alist[j], alist[j + 1]
    return alist


# print(inser_sort(alist))
print(func(alist))
点赞