诚之和:Python怎么实现冒泡排序
本篇内容主要讲解“Python怎么实现冒泡排序”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Python怎么实现冒泡排序”吧!
Python实现的源码的测试结果:
def bubble_sort(a_list): for pass_num in range(len(a_list) - 1, 0, -1): for i in range(pass_num): if a_list[i] > a_list[i + 1]: temp = a_list[i] a_list[i] = a_list[i + 1] a_list[i + 1] = temp def short_bubble_sort(a_list): exchanges = True pass_num = len(a_list) - 1 while pass_num > 0 and exchanges: exchanges = False for i in range(pass_num): if a_list[i] > a_list[i + 1]: exchanges = True temp = a_list[i] a_list[i] = a_list[i + 1] a_list[i + 1] = temp pass_num = pass_num - 1 a_list = [54,26,93,17,77,31,44,55,20] bubble_sort(a_list) print(a_list)
输出结果:
[17, 20, 26, 31, 44, 54, 55, 77, 93][20, 30, 40, 50, 60, 70, 80, 90, 100, 110]
赞 (0)