直观感受各种排序算法(一)
2020-04-01 18:35
16 查看
文章目录
各种排序算法对比
插入排序
1、直接插入排序
基本思想:每一步将一个待排序的数据插入到前面已经排好序的有序序列中,直到插完所有元素为止。
Python代码演示
def insert(l): n = len(l) for i in range(1,n): for j in range(i-1,-1,-1): if l[j] > l[j+1]: l[j],l[j+1] = l[j+1],l[j] else: break L = [15,61,56,12,35,68,9] insert(L) print(L) #[9, 12, 15, 35, 56, 61, 68]
结果展示
time_list = timeit.repeat(stmt='insert(L)',setup='from __main__ import insert;import numpy as np;L = np.random.random_integers(1, 10001, size=10000);',number=1,repeat=3) print(time_list) print(sum(time_list)/len(time_list)) """ size = 1000 [0.162421044, 0.16958592, 0.15284150600000002] 0.16161615666666665 size = 10000 [16.105381590999997, 16.267967523999996, 16.177776573000003] 16.183708562666666 """
这里用到的测试模块是
timeit,如果不知道怎么使用这里给出一个—>链接<—
分析总结
数据规模扩大10倍,执行时间翻了100倍。
直接插入不适合大规模数据,且执行速度太慢。
快速排序
Python代码演示
import timeit def sub_sort(l,low,high): k = l[low]#基数 while low < high:#循环判断条件 while l[high] > k and high > low: high -= 1 l[low] = l[high]#比基数小的往左边甩 while l[low] <= k and low < high: low += 1 l[high] = l[low]#比基数大的往右边帅 l[low] = k#将基数插入 return low#返回基数下标 def quick(l,low,high): if low < high:#执行条件判断 k = sub_sort(l,low,high)#获取基数 quick(l,low,k-1)#排序 基数左边 quick(l,k+1,high)#排序 基数右边 time_list = timeit.repeat(stmt='quick(L,0,len(L)-1)',setup='from __main__ import quick;import numpy as np;L = np.random.random_integers(1, 100001, size=10000);',number=1,repeat=3) print(time_list) print(sum(time_list)/len(time_list))
结果展示
""" size = 1000 [0.0036959930000000085, 0.003791104999999989, 0.003807105000000005] 0.003764734333333334 size = 10000 [0.05053102100000001, 0.05129990799999998, 0.050997242000000026] 0.05094272366666667 13倍 size = 100000 [0.652755284, 0.6358122030000001, 0.642734857] 0.6437674480000001 171倍 """
分析总结
数据规模扩大10倍,时间扩大13倍;数据规模扩大100倍,执行时间扩大171倍。
快排处理大规模数据快,对比直接插入排序简直不要太香。
希望大家自己跑着玩玩,感受算法带来的乐趣吧!!!
- 点赞
- 收藏
- 分享
- 文章举报
相关文章推荐
- 【轻松学排序算法】眼睛直观感受几种常用排序算法
- 【轻松学排序算法】眼睛直观感受几种常用排序算法
- 【轻松学排序算法】眼睛直观感受几种常用排序算法
- [直观学习排序算法] 视觉直观感受若干常用排序算法
- 眼睛直观感受几种常用排序算法
- 【轻松学排序算法】眼睛直观感受几种常用排序算法(转)
- 视觉直观感受7种常用的排序算法
- 眼睛直观感受几种常用排序算法
- 视觉直观感受7种常用的排序算法
- 视觉直观感受7种常用排序算法
- [转]直观感受排序算法
- 视觉直观感受若干常用排序算法
- 视觉直观感受7种常用的排序算法
- 视觉直观感受7种常用的排序算法
- 视觉直观感受 7 种常用的排序算法
- 视觉直观感受 7 种常用的排序算法
- 视觉直观感受 7 种常用的排序算法
- 眼睛直观感受几种常用排序算法
- 视觉直观感受 7 种常用的排序算法
- 眼睛直观感受几种常用排序算法