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程序设计有所帮助。
热门推荐
1 泰迪狗狗如何训练
3 狗狗训练图
5 狗狗训练方法
6 训练狗狗不咬人
8 敏捷训练狗狗
10 训练狗狗吃饭
11 泰迪狗狗训练
12 狗狗从多大开始训练
13 狗狗训练学校费用
14 怎么去训练狗狗
15 狗狗训练狗狗
16 狗狗训练教程
17 训练狗狗装死
18 泰迪狗狗的训练方法