用python实现冒泡排序和选择排序(Python经典编程案例)

北战南征 提交于 2019-11-28 11:08:08
1. 冒泡排序:
def bubble_sort(list):
    for i in range(0, len(list)):
        is_sorted = True
        for j in range(0, len(list) - i - 1):
            if list[j] > list[j + 1]:
                list[j], list[j + 1] = list[j + 1], list[j]
                is_sorted = False
        if is_sorted:
            return


list1 = [97, 3, 6, 1, 8, 5, -20, 100, 50, 200, -32, 123]
bubble_sort(list1)
print(list1)

执行结果如下图:
在这里插入图片描述

2. 选择排序:
def choose_sort(list):
    list_len = len(list)
    for i in range(0, list_len):
        for j in range(i + 1, list_len):
            if list[i] > list[j]:
                list[i], list[j] = list[j], list[i]
                

list1 = [3, 6, 1, 8, 5, -20, 100, 50, 200]
choose_sort(list1)
print(list1)

执行结果如下图:
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!