适当的Python SelectionSort

时间:2017-02-04 20:32:59

标签: python sorting

我正在尝试使用python学习选择排序,但不能让我的代码工作。一些援助将不胜感激。

def selection(seq):
    for x in range(len(seq)):
    temp = 0
        for y in range(1, len(seq)):
            if seq[y] < seq[temp]:
            temp = y
    if temp != 0:    
        seq[x], seq[temp] = seq[temp], seq[x]
    return seq

选择([12,38,2,18,15,1,19])

1 个答案:

答案 0 :(得分:2)

您为循环和初始化temp混合了索引。您可以使用以下代码修复它:

def selection(seq):
    for x in range(len(seq)):
        temp = x
        for y in range(x+1, len(seq)):
            if seq[y] < seq[temp]:
                temp = y
        seq[x], seq[temp] = seq[temp], seq[x]
    return seq

seq = [5, 3, 1, 2, 4]
print(selection(seq))