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程序设计有所帮助。