python選擇排序算法實(shí)例總結(jié)
更新時(shí)間:2015年07月01日 11:17:18 作者:pythoner
這篇文章主要介紹了python選擇排序算法,以三個(gè)實(shí)例以不同方法分析了Python實(shí)現(xiàn)選擇排序的相關(guān)技巧,需要的朋友可以參考下
本文實(shí)例總結(jié)了python選擇排序算法。分享給大家供大家參考。具體如下:
代碼1:
def ssort(V):
#V is the list to be sorted
j = 0
#j is the "current" ordered position, starting with the first one in the list
while j != len(V):
#this is the replacing that ends when it reaches the end of the list
for i in range(j, len(V)):
#here it replaces the minor value that it finds with j position
if V[i] < V[j]:
#but it does it for every value minor than position j
V[j],V[i] = V[i],V[j]
j = j+1
#and here's the addiction that limits the verification to only the next values
return V
代碼2:
def selection_sort(list):
l=list[:]
# create a copy of the list
sorted=[]
# this new list will hold the results
while len(l):
# while there are elements to sort...
lowest=l[0]
# create a variable to identify lowest
for x in l:
# and check every item in the list...
if x<lowest:
# to see if it might be lower.
lowest=x
sorted.append(lowest)
# add the lowest one to the new list
l.remove(lowest)
# and delete it from the old one
return sorted
代碼3
a=input("Enter the length of the list :")
# too ask the user length of the list
l=[]
# take a emty list
for g in range (a):
# for append the values from user
b=input("Enter the element :")
# to ask the user to give list values
l.append(b)
# to append a values in a empty list l
print "The given eliments list is",l
for i in range (len(l)):
# to repeat the loop take length of l
index=i
# to store the values i in string index
num=l[i]
# to take first value in list and store in num
for j in range(i+1,len(l)):
# to find out the small value in a list read all values
if num>l[j]:
# to compare two values which store in num and list
index=j
# to store the small value of the loop j in index
num=l[j]
# to store small charecter are value in num
tem=l[i]
# to swap the list take the temparary list stor list vlaues
l[i]=l[index]
# to take first value as another
l[index]=tem
print "After the swping the list by selection sort is",l
希望本文所述對(duì)大家的Python程序設(shè)計(jì)有所幫助。
相關(guān)文章
Python中numpy數(shù)組真值判斷的實(shí)現(xiàn)
在Python編程中,經(jīng)常需要對(duì)數(shù)組進(jìn)行真值判斷,本文就來介紹一下Python中numpy數(shù)組真值判斷的實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的可以了解一下2023-09-09
基于Python實(shí)現(xiàn)的戀愛對(duì)話小程序詳解
這篇文章主要介紹了基于Python制作一個(gè)戀愛對(duì)話小程序,文章詳細(xì)介紹了小程序的實(shí)現(xiàn)過程,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)學(xué)習(xí)2022-01-01
Pandas實(shí)現(xiàn)Excel文件讀取,增刪,打開,保存操作
Pandas?是一種基于?NumPy?的開源數(shù)據(jù)分析工具,用于處理和分析大量數(shù)據(jù)。本文將通過Pandas實(shí)現(xiàn)對(duì)Excel文件進(jìn)行讀取、增刪、打開、保存等操作,需要的可以參考一下2023-04-04
Pycharm添加虛擬解釋器報(bào)錯(cuò)問題解決方案
這篇文章主要介紹了Pycharm添加虛擬解釋器報(bào)錯(cuò)問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10
Python實(shí)現(xiàn)給文件添加內(nèi)容及得到文件信息的方法
這篇文章主要介紹了Python實(shí)現(xiàn)給文件添加內(nèi)容及得到文件信息的方法,可實(shí)現(xiàn)從文件開頭添加內(nèi)容的功能,需要的朋友可以參考下2015-05-05

