在python中实现选择排序?

时间:2016-10-10 20:37:40

标签: python sorting selection-sort

这可能看起来像一个简单的问题但是当我尝试在Python中实现选择排序时,我没有得到排序列表。我的实施有问题吗?

>>> sample = [['A','T','N','N'],['T', 'C', 'C', 'C']],[['A','T','T','N'],['T', 'T', 'C', 'C']]
>>> [[filterJoin(s) for s in t] for t in sample]
[['AT', 'TCCC'], ['ATT', 'TTCC']]

这是我得到的:

def selectionSort (B, annotate=True):
    for i in range(len(A)):
    for j in range(1,len(A)):
        if(A[i] > A [j]):
            A[i], A[j] = A[j], A[i]



A = [5, 4, 3, 2, 1]
A_sorted = selectionSort (A)
print ("Sorted " + str(A) + " = " + str(A_sorted))

A = [10, 7, 8, 40, 2, 5]
A_sorted = selectionSort (A)
print ("Sorted " + str(A) + " = " + str(A_sorted))

1 个答案:

答案 0 :(得分:0)

可以尝试一下。你的j索引也是固定的,需要根据i来改变。

def selectionSort (A, annotate=True):
    for i in range(len(A)):
      for j in range(i+1,len(A)):
          if(A[i] > A [j]):
              A[i], A[j] = A[j], A[i]

    return A    

检查值:

A = [5, 4, 3, 2, 1]
print selectionSort(A)
>>[1, 2, 3, 4, 5]

此外,如果要打印旧数组和新数组,可能需要通过引用它来保存旧数组。

A = [5, 4, 3, 2, 1]
Arr=A[:]
A_sorted=selectionSort(A)
print ("Sorted " + str(Arr) + " = " + str(A_sorted))