冒泡法:两两比较大小,交换位置 m=[1,3,4,2,5,7,6,8,9,11,32,42,52,13,15,26,19,57,53,49,80,70,69,58,48,34,67,89,92,46,75,71,73,50,48,84,24,20,28,53] count=0 count_c=0 for i in range(len(m)): flag=False for j in range(len(m)-i-1): count+=1 if m[j]<m[j+1]: m[j],m[j+1]=m[j+1],m[j] count_c+=1 flag=True if not flag: break print(m,count,count_c) 简单选择排序:两两比较大小,找出极值,和两端交换 m=[1,3,4,2,5,7,6,8,9,11,32,42,52,13,15,26,19,57,53,49,80,70,69,58,48,34,67,89,92,46,75,71,73,50,48,84,24,20,28,53] count=0 count_c=0 for i in range(len(m)//2): maxindex=i minindex=-i-1 for j in range(i+1,len(m)-i): count+=1 if m[maxindex]<m[j]: maxindex=j if m[minindex]>m[-j-1]: minindex=-j-1 if i !=maxindex: m[i],m[maxindex]=m[maxindex],m[i] count_c+=1 if i ==minindex or i ==len(m)+minindex: minindex=maxindex if -i-1 != minindex: m[-i-1],m[minindex]=m[minindex],m[-i-1] count_c+=1 print(m,count,count_c) 直接插入排序:在开头插入一个数,从第二个开始比较,通过开头的数相互替换 m=[1,3,4,2,5,7,6,8,9,11,32,42,52,13,15,26,19,57,53,49,80,70,69,58,48,34,67,89,92,46,75,71,73,50,48,84,24,20,28,53] num=[0]+m count=0 count_c=0 for i in range(2,len(num)): num[0]=num[i] j=i-1 count+=1 if num[j]<num[0]: while num[j]<num[0]: num[j+1]=num[j] count_c+=1 j-=1 num[j+1]=num[0] num.pop(0) print(num,count,count_c)
本文来自投稿,不代表Linux运维部落立场,如若转载,请注明出处:http://www.178linux.com/87489