1. 程式人生 > >python冒泡排序

python冒泡排序

post gpo list 控制 blog for 循環 最大 pos

對列表進行冒泡排序

def bubble_sort(raw_list):

    # 控制循環次數 n-1
    for times in range(len(raw_list) - 1):

        # 每次循環中需要比較的次數 每執行1次後會將本次比較中的最大值移動到末尾
        # 下次可以不在進行比較 n-times 由於比較時使用下標 n-times-1
        for index in range(len(raw_list) - times - 1):
            if raw_list[index + 1] < raw_list[index]:
                raw_list[index], raw_list[index + 1] = raw_list[index + 1], raw_list[index]
    print(raw_list)


if __name__ == ‘__main__‘:
    alist = [3, 1, 4, 5, 2, 1, 7]
    bubble_sort(alist)

-----------------------
[1, 1, 2, 3, 4, 5, 7]

python冒泡排序