数据结构之排序算法
来源:互联网 发布:盒饭网络销售怎么做 编辑:程序博客网 时间:2024/06/07 00:30
一、冒泡排序
比较两个相邻的项,并交换无序的项。需要遍历n-1次,总共的比较次数为 1/2n^2 - 1/2n,这仍然是 O(n^2 )比较。至于交换的次数也会影响效率,平均来说,交换了一半的时间。
def shortBubbleSort(alist): exchanges = True passnum = len(alist) - 1 while passnum > 0 and exchanges: for i in range(passnum): if alist[i] > alist[i + 1]: exchanges = True temp = alist[i] alist[i] = alist[i + 1] alist[i + 1] = temp else: exchanges = False passnum = passnum - 1alist = [20, 30, 40, 90, 50, 60, 70, 80, 100, 110]shortBubbleSort(alist)print(alist)
二、选择排序
与冒泡排序一样,他它的比较次数也是 1/2n^2 - 1/2n,但不是每一次无序都交换,而是找出最大值,放到最后一个位置即可,平均认为,遍历一次,交换一次。
def chooseSort(alist): passnum = len(alist) - 1 while passnum>0 : positionofMax = 0 for j in range(1,passnum+1): if alist[j]>alist[positionofMax]: positionofMax = j temp = alist[positionofMax] alist[positionofMax] = alist[passnum] alist[passnum] = temp passnum = passnum -1alist = [20, 30, 150, 90, 50, 60, 70, 80, 100, 110]chooseSort(alist)print(alist)
三、插入排序
方法:假设有一个项(位置 0 )的列表已经被排序,针对已经排序的子列表中的项检查当前项。当我们回顾已经排序的子列表时,我们将那些更大的项移动到右边。 当我们到达较小的项或子列表的末尾时,可以插入当前项。
时间复杂度:也要比较1+2+3+….+n-1 = 1/2n^2 - 1/2n,但插入排序发现当前要插入的值较小时,是将列表中的值上移,最后在插入,移位操作只需要交换大约三分之一的处理工作。因为仅执行一次分配。在基准研究中,插入排序有非常好的性能。
def insertionSort(alist): for index in range(1,len(alist)): currentvalue = alist[index] position = index while position>0 and alist[position-1]>currentvalue: alist[position]=alist[position-1] position = position-1 alist[position]=currentvaluealist = [54,26,93,17,77,31,44,55,20]insertionSort(alist)print(alist)
四、shell排序
阅读全文
0 0
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- 数据结构之排序算法
- Java网络爬虫(八)--使用多线程进行百度图片的抓取
- Unity/Animation -- 创建Animation Clip
- 通过DiskLruCache以及LruCache来构建自己项目的图片缓存框架
- Android Studio Java文件和Kotlin文件的转换
- 172.n1-使用sharedpreference将读取的新闻标记为灰色
- 数据结构之排序算法
- ThreadLocal的使用
- LeetCode 34. Search for a Range
- Remove Element
- 253. Meeting Rooms II
- cors跨域请求,重复提交问题
- 123
- HDFS 指令(四)find,help,setfatter,truncate,usage
- 【python学习笔记】13:用梯度下降法求解最优值问题