冒泡是最费时的排序,但可以自定义更多步骤。
短冒泡确实可以加快性能。
# coding = utf-8
# ========冒泡排序========
def bubble_sort(a_list):
loop_count = 0
swap_count = 0
for i in range(len(a_list)):
loop_count += 1
for j in range(i+1, len(a_list)):
# print(a_list)
loop_count += 1
if a_list[i] > a_list[j]:
swap_count += 1
a_list[i], a_list[j] = a_list[j], a_list[i]
print('======== bubble_sort loop_count========', loop_count)
print('========bubble_sort swap_count========', swap_count)
# '========短冒泡排序========
def short_bubble_sort(a_list):
loop_count = 0
swap_count = 0
exchange = True
pass_num = len(a_list) - 1
while pass_num > 0 and exchange:
loop_count += 1
exchange = False
for i in range(pass_num):
loop_count += 1
if a_list[i] > a_list[i+1]:
swap_count += 1
exchange = True
temp = a_list[i]
a_list[i] = a_list[i + 1]
a_list[i + 1] = temp
pass_num -= 1
print('========short_bubble_sort loop_count========', loop_count)
print('========short_bubble_sort swap_count========', swap_count)
my_list = [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36]
bubble_sort(my_list)
print(my_list)
my_short_list = [4, 5, 7, 2, 9, 7, 9, 54, 765, 45, 9876, 34, 12343, 36]
short_bubble_sort(my_short_list)
print(my_short_list)
D:\cheng\test\Scripts\python.exe D:/GIT/Prism4K/Prism4K/document/tests.py ======== bubble_sort loop_count======== 105 ========bubble_sort swap_count======== 15 [2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343] ========short_bubble_sort loop_count======== 69 ========short_bubble_sort swap_count======== 15 [2, 4, 5, 7, 7, 9, 9, 34, 36, 45, 54, 765, 9876, 12343] Process finished with exit code 0