升级版的冒泡法----鸡尾酒排序法(先从前往后,然后从后往前)

直接看代码:

import random

list2 = [random.randint(1, 9) for _ in range(9)]
print(list2)
count_swap_2 = 0
count_iter_2 = 0

list3 = list2.copy()
count_swap_3 = 0
count_iter_3 = 0

#升级版的冒泡法:鸡尾酒排序法(交换次数一样,迭代次数减少了.)
for i in range(len(list2)):
    flag = True
    for j in range(i, len(list2)-i-1):
        count_iter_2 += 1
        if list2[j] > list2[j+1]:
            list2[j], list2[j+1] = list2[j+1], list2[j]
            count_swap_2 += 1
            flag = False
    if flag:
        break
        
    for k in range(len(list2)-1-i, i, -1):
        if list2[k] < list2[k-1]:
            list2[k], list2[k-1] = list2[k-1], list2[k]
            count_swap_2 += 1
            flag = False
    if flag:
        break
print(list2, count_swap_2, count_iter_2)

#下面是原始的冒泡法排序:
for i in range(len(list3)):
    flag = True
    for j in range(len(list3)-i-1):
        count_iter_3 += 1
        if list3[j] > list3[j+1]:
            list3[j], list3[j+1] = list3[j+1], list3[j]
            count_swap_3 += 1
            flag = False
    if flag:
        break

print(list3, count_swap_3, count_iter_3)

对比
交换次数一样多, 但迭代次数减少了.

你可能感兴趣的:(python)