选择排序小谈

来源:互联网 发布:js如何获取input的值 编辑:程序博客网 时间:2024/05/21 13:32

选择排序顾名思义(以递增排序为例,使用Python语言):选择(选择最小的元素) + 排序(放置选择到的数到相应位置)

1. 选择——在一堆数字之中找到最小的数是很容易完成的:

def min(list):    min = 0    for i in range( len(list) ):        if list[min] > list[i]:           min = i     return minlist = [3, 4, 5, 9, 2]index = min(list)print list[index], index

使用函数的方式供下面步骤调用。


2.排序——将数字放置到合适的位置有很多种方法:

其一:生成一个新列表,每找到一个最小值就加入到新列表的最后——使用append函数(其中要注意把找到的最小值从原列表中剔除)。整个实现如下:

lst = [3, 4, 5, 9, 2, 6, 7, 8, 20, 10]list_done = list()for i in range( len(lst)):    mi = min(lst)    list_done.append( lst[mi] )        lst.pop( mi)print list_done

其二:与列表中的第一个交换。

列表中有多少数,就要循环多少次(当然最后一个数似乎没有必要比较自然而然的就是最大的),每次循环都将找到的最小的数与子列表 的第一个进行交换。

(子列表:每一次循环都刨除第一个数,因为第一个数就是之前找到的最小的数放到第一位的,第一次循环的子列表就是整个列表。子列表使用Python的切片操作实现)

def swap(i, mi):    print 'current i , mi is:',lst[i],lst[mi]    temp = lst[i]    lst[i] = lst[mi]    lst[mi] = temp    lst = [3, 4, 5, 9, 2, 6, 7, 8, 20, 10,1, 0, 50, 5]for i in range( len(lst) ):    nLst = lst[i:]    print 'current the list is:', lst    print 'current the sub list is:', nLst    print 'current index is:', i    mi = min( nLst )    swap(i, mi+i)   #use index as parameter or will cause mistakeprint lst
注意细节上的逻辑错误,在swap中,第二个参数不能够直接传mi,因为 mi 是在砍掉了 i 项之后的 nLst 中的位置 ≠ lst中的位置, 所以需要给mi 补上 i 才是 lst 中正确的位置。








0 0
原创粉丝点击