python选择排序算法实例总结
本文实例总结了python选择排序算法。分享给大家供大家参考。具体如下:
代码1:
defssort(V): #Visthelisttobesorted j=0 #jisthe"current"orderedposition,startingwiththefirstoneinthelist whilej!=len(V): #thisisthereplacingthatendswhenitreachestheendofthelist foriinrange(j,len(V)): #hereitreplacestheminorvaluethatitfindswithjposition ifV[i]<V[j]: #butitdoesitforeveryvalueminorthanpositionj V[j],V[i]=V[i],V[j] j=j+1 #andhere'stheaddictionthatlimitstheverificationtoonlythenextvalues returnV
代码2:
defselection_sort(list): l=list[:] #createacopyofthelist sorted=[] #thisnewlistwillholdtheresults whilelen(l): #whilethereareelementstosort... lowest=l[0] #createavariabletoidentifylowest forxinl: #andcheckeveryiteminthelist... ifx<lowest: #toseeifitmightbelower. lowest=x sorted.append(lowest) #addthelowestonetothenewlist l.remove(lowest) #anddeleteitfromtheoldone returnsorted
代码3
a=input("Enterthelengthofthelist:")
#tooasktheuserlengthofthelist
l=[]
#takeaemtylist
forginrange(a):
#forappendthevaluesfromuser
b=input("Entertheelement:")
#toasktheusertogivelistvalues
l.append(b)
#toappendavaluesinaemptylistl
print"Thegivenelimentslistis",l
foriinrange(len(l)):
#torepeatthelooptakelengthofl
index=i
#tostorethevaluesiinstringindex
num=l[i]
#totakefirstvalueinlistandstoreinnum
forjinrange(i+1,len(l)):
#tofindoutthesmallvalueinalistreadallvalues
ifnum>l[j]:
#tocomparetwovalueswhichstoreinnumandlist
index=j
#tostorethesmallvalueoftheloopjinindex
num=l[j]
#tostoresmallcharecterarevalueinnum
tem=l[i]
#toswapthelisttakethetempararyliststorlistvlaues
l[i]=l[index]
#totakefirstvalueasanother
l[index]=tem
print"Aftertheswpingthelistbyselectionsortis",l
希望本文所述对大家的Python程序设计有所帮助。
热门推荐
10 高一祝福语简短 励志
11 立秋节气简短祝福语
12 简短公司周年祝福语大全
13 中考感言简短祝福语大全
14 体育老师简短祝福语
15 干杯生日祝福语简短独特
16 特别简短的祝福语老师
17 朋友坐车走了祝福语简短
18 给英雄的祝福语简短