Python实现排序算法:冒泡排序,插入排序,选择排序,快速排序,希尔排序
生活随笔
收集整理的這篇文章主要介紹了
Python实现排序算法:冒泡排序,插入排序,选择排序,快速排序,希尔排序
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
2019獨角獸企業重金招聘Python工程師標準>>>
import?sys,?getopt,?randomdef?bubble_sort(seq):for?i?in?range(len(seq)):for?j?in?range(1,len(seq)):if?seq[j-1]>seq[j]:seq[j-1],?seq[j]=?seq[j],?seq[j-1]return?seqdef?insertion_sort(seq):for?i?in?range(1,len(seq)):tmp=seq[i]pos=i;for?j?in?range(i-1,-1,-1):if?seq[j]>tmp:seq[j+1]=seq[j]pos=jseq[pos]=tmpreturn?seqdef?selection_sort(seq):for?i?in?range(len(seq)):min_index=i;for?j?in?range(i,len(seq)):if?seq[j]<seq[min_index]:min_index=jseq[i],seq[min_index]=seq[min_index],seq[i]return?seqdef?partition(seq,p,l,r):pivot?=?seq[p]seq[p],seq[r]=seq[r],seq[p]p_pos?=?lfor?i?in?range(l,r):if?seq[i]<=pivot:seq[i],seq[p_pos]=seq[p_pos],seq[i]p_pos=p_pos+1seq[p_pos],seq[r]=seq[r],seq[p_pos]return?p_posdef?quick_sort(seq,left,right):if?left?<?right:pivot?=?random.randint(left,right)mid?=?partition(seq,pivot,left,right)quick_sort(seq,left,mid-1)quick_sort(seq,mid+1,right)return?seqdef?shell_sort(seq):incr?=?len(seq)/2while(incr>=1):for?i?in?range(incr,len(seq)):tmp=seq[i]pos=i;for?j?in?range(i-incr,-1,-incr):if?seq[j]>tmp:seq[j+incr]=seq[j]pos=jseq[pos]=tmpincr?=?incr/2return?seqdef?usage():print?'Usage:?python?sort.py?sorttype[-q|-i|-b|-s|--shell]?sequence'print?'Example:?python?sort.py?-q?11,32,3,24,5'def?main():try:if(len(sys.argv)==1)?or?(len(sys.argv)!=3):raise?Exception()else:opts,args=getopt.getopt(sys.argv[1:],'qibs',['shell'])if?len(args)>0:seq=[]tmp=args[0].split(',')for?i?in?tmp:seq.append(int(i))else:raise?Exception()for?opt?in?opts:if?opt[0]?=='-q':print?quick_sort(seq,0,len(seq)-1)elif?opt[0]?=='-i':print?insertion_sort(seq)elif?opt[0]?=='-b':print?bubble_sort(seq)elif?opt[0]?=='-s':print?selection_sort(seq)elif?opt[0]?=='--shell':print?shell_sort(seq)except?Exception,e:usage()print?esys.exit() if?__name__?=="__main__":main()轉載于:https://my.oschina.net/Sheamus/blog/395503
總結
以上是生活随笔為你收集整理的Python实现排序算法:冒泡排序,插入排序,选择排序,快速排序,希尔排序的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 微信在公众号增开了新广告位 这次是在图文
- 下一篇: Android开发过程中内存泄露检测