这看起来可能是一个简单的问题,但是当我尝试在Python中实现选择排序时,我没有得到一个排序列表。我的实现有什么问题吗?子设置可能是一个问题。
source = [4,2,1,10,5,3,100]
for i in range(len(source)):
  mini = min(source[i:]) #find minimum element
  min_index = source[i:].index(mini)-1 #find index of minimum element
  source[i:][min_index]= source[i:][0] #replace element at min_index with first element
  source[i:][0] = mini                  #replace first element with min element
print source发布于 2017-01-04 04:07:21
def selSort(L):
    """
    Find the smallest element in the list and put it (swap it) in the first location, 
    Find the second element and put it (swap it) in the second locaiton, and so on. 
    """
    for i in range(len(L) - 1):
        minIndx = i
        minVal= L[i]
        j = i + 1
        while j < len(L):
            if minVal > L[j]:
                minIndx = j
                minVal= L[j]
            j += 1
        temp = L[i]
        L[i] = L[minIndx]
        L[minIndx] = temp 
    return L呼叫:
print( selSort([120,11,0,1,3,2,3,4,5,6,7,8,9,10]) )输出
[0, 1, 2, 3, 3, 4, 5, 6, 7, 8, 9, 10, 11, 120]https://stackoverflow.com/questions/15235264
复制相似问题