python選擇排序算法實例總結(jié)
更新時間:2015年07月01日 11:17:18 作者:pythoner
這篇文章主要介紹了python選擇排序算法,以三個實例以不同方法分析了Python實現(xiàn)選擇排序的相關(guān)技巧,需要的朋友可以參考下
本文實例總結(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
希望本文所述對大家的Python程序設(shè)計有所幫助。
相關(guān)文章
Python3時間轉(zhuǎn)換之時間戳轉(zhuǎn)換為指定格式的日期方法詳解
這篇文章主要介紹了Python3時間轉(zhuǎn)換之時間戳轉(zhuǎn)換為指定格式的日期,需要的朋友可以參考下2021-04-04
Python中的JSON?Pickle?Shelve模塊特性與區(qū)別實例探究
在Python中,處理數(shù)據(jù)序列化和持久化是極其重要的,JSON、Pickle和Shelve是三種常用的模塊,它們提供了不同的方法來處理數(shù)據(jù)的序列化和持久化,本文將深入研究這三個模塊,探討它們的特性、用法以及各自的優(yōu)缺點2024-01-01
使用python繪制人人網(wǎng)好友關(guān)系圖示例
這篇文章主要介紹了使用python繪制人人網(wǎng)好友關(guān)系圖示例,需要的朋友可以參考下2014-04-04
如何解決django配置settings時遇到Could not import settings ''conf.loca
這里記錄一下在項目中遇到django配置settings時遇到Could not import settings 'conf.local'的解決方法,有同樣問題的小伙伴們參考下吧2014-11-11

