【算法】python-选择排序、冒泡排序、插入排序

a = [5, 4, 3, 2, 1, 0]
len_a = len(a)


# 选择排序
def selection_sort(a: list):
    if a is None or len_a < 2:
        return

    for i in range(len_a):
        min_index = i
        for j in range(i + 1, len_a):
            if a[j] < a[min_index]:
                min_index = j
        a[i], a[min_index] = a[min_index], a[i]
    print(a)


# 冒泡排序
def bubble_sort(a: list):
    if a is None or len_a < 2:
        return

    for i in range(len_a, 0, -1):
        for j in range(i):
            if j == 0:
                continue
            if a[j] < a[j - 1]:
                a[j], a[j - 1] = a[j - 1], a[j]
    print(a)


# 插入排序
def insertion_sort(a: list):
    if a is None or len_a < 2:
        return

    for i in range(len_a + 1):
        for j in range(i - 1, 0, -1):
            if a[j] < a[j - 1]:
                a[j], a[j - 1] = a[j - 1], a[j]

    print(a)


if __name__ == "__main__":
    # selection_sort(a)
    # bubble_sort(a)
    insertion_sort(a)

 

posted @ 2020-07-13 22:51  fengzx120  阅读(183)  评论(0编辑  收藏  举报