Python3 实现选择排序

选择排序

Python
重复(元素个数-1)次 把第一个没有排序过的元素设置为最小值 遍历每个没有排序过的元素 如果元素 < 现在的最小值 将此元素设置成为新的最小值 将最小值和第一个没有排序过的位置交换 # -*- coding: utf-8 -*- """ @author:songhao @file: c1.py @time: 2017/12/25 """ def findsmallest(a): """ 获取 列表中的最小值 :param a: list :return: 返回最小值的索引 """ a_smallest = a[0] a_smallest_index = 0 for x in range(1, len(a)): if a[x] < a_smallest: a_smallest = a[x] a_smallest_index = x return a_smallest_index def selection_sort(arr): new_arr = [] for i in range(len(arr)): # print(i) smallset = findsmallest(arr) new_arr.append(arr.pop(smallset)) ''' pop(...) method of builtins.list instance L.pop([index]) -> item -- remove and return item at index (default last). Raises IndexError if list is empty or index is out of range. (END) ''' # 取出最小值, append new_arr return new_arr if __name__ == '__main__': print("取出最小值") d = [33, 4, 42, 3, 5, 1] mind = findsmallest(d) print(mind) print("排序") sd = selection_sort(d) print(sd)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
重复(元素个数 - 1)次
把第一个没有排序过的元素设置为最小值
遍历每个没有排序过的元素
如果元素 & lt ; 现在的最小值
将此元素设置成为新的最小值
将最小值和第一个没有排序过的位置交换
 
# -*- coding: utf-8 -*-
& quot ; & quot ; & quot ;
@ author : songhao
@ file : c1 . py
@ time : 2017 / 12 / 25
& quot ; & quot ; & quot ;
 
 
def findsmallest ( a ) :
     & quot ; & quot ; & quot ;
    获取 列表中的最小值
     : param a : list
     : return : 返回最小值的索引
     & quot ; & quot ; & quot ;
     a_smallest = a [ 0 ]
     a_smallest_index = 0
     for x in range ( 1 , len ( a ) ) :
         if a [ x ] & lt ; a_smallest :
             a_smallest = a [ x ]
             a_smallest_index = x
     return a_smallest_index
 
 
def selection_sort ( arr ) :
     new_arr = [ ]
     for i in range ( len ( arr ) ) :
         # print(i)
         smallset = findsmallest ( arr )
         new_arr . append ( arr . pop ( smallset ) )
     '''
    pop(...) method of builtins.list instance
    L.pop([index]) -> item -- remove and return item at index (default last).
    Raises IndexError if list is empty or index is out of range.
    (END)
    '''
     # 取出最小值, append new_arr
     return new_arr
 
 
if __name__ == '__main__' :
     print ( & quot ;取出最小值 & quot ; )
     d = [ 33 , 4 , 42 , 3 , 5 , 1 ]
     mind = findsmallest ( d )
     print ( mind )
     print ( & quot ;排序 & quot ; )
     sd = selection_sort ( d )
     print ( sd )




  • zeropython 微信公众号 5868037 QQ号 5868037@qq.com QQ邮箱
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值