Home  >  Article  >  Backend Development  >  python选择排序算法的实现代码

python选择排序算法的实现代码

WBOY
WBOYOriginal
2016-06-16 08:46:131364browse

1.算法:
对于一组关键字{K1,K2,…,Kn}, 首先从K1,K2,…,Kn中选择最小值,假如它是 Kz,则将Kz与 K1对换;
然后从K2,K3,… ,Kn中选择最小值 Kz,再将Kz与K2对换。
如此进行选择和调换n-2趟,第(n-1)趟,从Kn-1、Kn中选择最小值 Kz将Kz与Kn-1对换,最后剩下的就是该序列中的最大值,一个由小到大的有序序列就这样形成。

2.python 选择排序代码:

复制代码 代码如下:

def selection_sort(list2):
    for i in range(0, len (list2)):
        min = i
        for j in range(i + 1, len(list2)):
            if list2[j]                 min = j
        list2[i], list2[min] = list2[min], list2[i]  # swap

结果为:[2, 3, 4, 21, 33, 44, 45, 67]

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn