008 Python语法之冒泡排序-插入排序
2017-07-05 18:58
267 查看
简书地址:http://www.jianshu.com/p/c7a38899e715
普通冒泡排序(比较次数42)
list1 = [7, 1, 2, 3, 4, 5, 6] length = len(list1) for x in range(0, length - 1): for y in range(0, length - 1): if list1[y] > list1[y + 1]: list1[y], list1[y + 1] = list1[y + 1], list1[y] print(list1)
更新版冒泡排序(比较次数21)
list1 = [7, 1, 2, 3, 4, 5, 6] for x in range(0, length - 1): for y in range(0, length - 1 - x): if list1[y] > list1[y + 1]: list1[y], list1[y + 1] = list1[y + 1], list1[y] print(list1)
究极版冒泡排序(比较次数11)
# 究极版冒泡排序 list1 = [7, 1, 2, 3, 4, 5, 6] length = len(list1) for i in range(0, length - 1): bool = True for j in range(0, length - 1 - i): print(list1) if list1[j] > list1[j + 1]: list1[j], list1[j + 1] = list1[j + 1], list1[j] bool = False if bool: break
插入排序
def insertSort(list1): length = len(list1) temp = 0 # 进行len - 1 次循环,每次循环都将下标为i的元素插入到它前面已经排好序的队列中 for i in range(1, length): if list1[i] < list1[i - 1]: temp = list1[i] while i > 0 and temp < list1[i - 1]: list1[i] = list1[i - 1] i -= 1 list1[i] = temp list1 = [7, 1, 2, 3, 4, 5, 6] insertSort(list1) print(list1)
模块引用
注意init文件需要有,定义module用的import 文件夹名.文件夹名....py文件名
求三个数的最大值
第一版
def max(x, y, z): max1 = x if max1 < y: max1 = y if max1 < z: max1 = z return max1 print(max(1,2,3))
第二版
def max(x, y, z): max1 = x max1 = max1 if max1 > y else y max1 = max1 if max1 > z else z return max1 print(max(1,2,3))
总结
后面会出一篇介绍8大排序的文章,总结下排序的使用。
相关文章推荐
- python排序算法-冒泡排序,选择排序,直接插入排序,希尔排序,归并排序,快速排序,堆排序
- python 冒泡排序 选择排序 插入排序的对比分析
- 排序算法总结(冒泡排序、直接插入排序、希尔排序)(python实现)
- 冒泡排序、选择排序、直接插入排序(java实现)
- 排序算法之直接插入排序、选择排序和冒泡排序
- 基础排序——冒泡排序、选择排序、插入排序的讲解、代码实现
- OC下的冒泡排序,直接插入排序,折半插入排序
- 插入排序,选择排序,冒泡排序等常用排序算法(java实现)
- python插入排序
- 插入排序和冒泡排序
- 排序算法(快速排序、直接插入排序、直接选择、冒泡排序)
- 经典算法:二分查找、插入排序、选择排序、冒泡排序
- Java选择排序、冒泡排序、直接插入排序与二分查找
- (三)插入排序-python实现
- Java基础篇之----排序(快速排序、冒泡排序、堆排序、简单选择排序、 希尔排序、直接插入排序)
- 第16周项目1-验证算法(3)冒泡排序 直接插入排序
- 排序算法---基础算法(冒泡排序,快速排序,选择排序,直接插入排序,桶排序)
- 直接插入排序、折半插入排序、冒泡排序、快速排序的算法实现
- 冒泡排序,选择排序,插入排序的比较
- 数据结构与算法:七种排序算法总结(冒泡排序、选择排序、直接插入排序、希尔排序、堆排序、归并排序、快速排序)