Python实现排序方法常见的四种

1.冒泡排序,相邻位置比较大小,将比较大的(或小的)交换位置

def maopao(a):for i in range(0,len(a)):for j in range(0,len(a)-i-1):if a[j]>a[j+1]:temp = a[j+1]a[j+1] = a[j]a[j] = temp#print(a)#print(a)print(a)

2.选择排序,遍历选择一个最小的数与当前循环的第一个数交换
def xuanze(a):for i in range(0,len(a)):k=itemp = a[i]for j in range(i,len(a)):if a[j]
3.快速排序:将子段的第一个元素做为中值,先从右向左遍历,如过比中值大high-1,如果比中值小,将这个值放到low那里。
然后从左向右开始遍历,如果左侧的比中值大,将他放到high那里。当low>=high时,将中值的值赋给low
(1.以下为参照公众号中的做法:
a =[7,1,3,2,6,54,4,4,5,8,12,34]def sort(a,low,high): while low < high:temp = a[low]while low < high and a[high]>=temp:high = high-1a[low]=a[high]while low
(2.以下是参照网上的做法:
在做快速排序时一直各种问题,是因为地柜那里没有考虑清楚,一直把low的值赋值为0了,实际上应该是不固定的low值,他每个子循环不定。
'''遇到问题没人解答?小编创建了一个Python学习交流群:531509025寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!'''a =[7,1,3,2,6,54,4,4,5,8,12,34]def sort(a,low,high): while low < high:temp = a[low]while low < high and a[high]>=temp:high = high-1while low
4.插入排序:从左向右遍历,依次选取数值,从数值的左侧从右向左遍历,选择第一个比他小的数值的右侧插入该数值,其他数值依次向后赋值
#插入排序a =[7,1,3,2,6,54,4,4,5,8,12,34]for i in range(0,len(a)-1):temp=a[i+1]j=i+1while j>=0 and temp=-1:k= i+1while k>=j:a[k]=a[k-1]k=k-1print(a)a[j]=tempprint(a)

插入排序方法2,用到了列表的a.insert(1,2)和清楚a[2:3]=[],这样可以少用一个循环
a =[7,1,3,2,6,54,4,4,5,8,12,34]for i in range(1,len(a)-1):temp=a[i]j=i-1while j>=0 and temp<=a[j]:print(temp)j=j-1if j >=-1:a[i:i+1]=[]a.insert(j+1,temp)print(a)print(a)

【Python实现排序方法常见的四种】到此这篇关于Python实现排序的四种方法的文章就介绍到这了,更多相关python排序方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读