python选择排序算法实例总结

yipeiwu_com5年前Python基础

本文实例总结了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程序设计有所帮助。

相关文章

对python 读取线的shp文件实例详解

如下所示: import shapefile sf = shapefile.Reader("E:\\1.2\\cs\\DX_CSL.shp") shapes = sf.shapes(...

TensorFlow用expand_dim()来增加维度的方法

TensorFlow中,想要维度增加一维,可以使用tf.expand_dims(input, dim, name=None)函数。当然,我们常用tf.reshape(input, sha...

Golang与python线程详解及简单实例

Golang与python线程详解及简单实例 在GO中,开启15个线程,每个线程把全局变量遍历增加100000次,因此预测结果是 15*100000=1500000. var sum...

深入理解NumPy简明教程---数组3(组合)

前两篇文章对NumPy数组做了基本的介绍,本篇文章对NumPy数组进行较深入的探讨。首先介绍自定义类型的数组,接着数组的组合,最后介绍数组复制方面的问题。 自定义结构数组 通过NumP...

python使用tornado实现登录和登出

本文实例为大家分享了tornado实现登录和登出的具体代码,供大家参考,具体内容如下 main.py如下: import tornado.httpserver import torn...