Python 冒泡,选择,插入排序使用实例
最近学习了python基础,写一下3大排序练练手:
''' Createdon2013-8-23 @author:codegeek ''' //冒泡排序 defbubble_sort(seq): foriinrange(len(seq)): forjinrange(i,len(seq)): ifseq[j]<seq[i]: tmp=seq[j] seq[j]=seq[i] seq[i]=tmp //选择排序 defselection_sort(seq): foriinrange(len(seq)): position=i forjinrange(i,len(seq)): ifseq[position]>seq[j]: position=j ifposition!=i: tmp=seq[position] seq[position]=seq[i] seq[i]=tmp //插入排序 definsertion_sort(seq): iflen(seq)>1: foriinrange(1,len(seq)): whilei>0andseq[i]<seq[i-1]: tmp=seq[i] seq[i]=seq[i-1] seq[i-1]=tmp i=i-1 // if__name__=="__main__": print"--------bubble_sort-------------" seq=[22,1,33,4,7,6,8,9,11] bubble_sort(seq) printseq print"--------selection_sort-------------" seq=[88,44,33,4,7,6,8,9,11] selection_sort(seq) printseq print"--------insertion_sort-------------" seq=[777,44,33,4,7,6,1111,100,11] insertion_sort(seq) printseq
以上就是3则Python中冒泡,选择,插入排序的代码及使用方法了,希望小伙伴们能够喜欢。