在python中排序列表而不使用内置的.sort()

时间:2015-03-12 20:29:35

标签: python python-3.x

def sortList(myList):
    sortList = []
    while myList:
        Min = myList[0]
        for i in myList:
            if i < Min:
                Min = i
        sortList.append(Min)
    return sortList

此函数应该使用mylist并返回mylist,而不使用.sort()。任何人都可以帮我弄清楚我的错误让这个程序运行?

1 个答案:

答案 0 :(得分:0)

这就是你的意思:

def sort(L):
    answer = []
    while L:
        min = L[0]
        minInd = 0
        for i in range(len(L)):
            num = L[i]
            if num < min:
                min = num
                minInd = i
        answer.append(num)
        L.pop(minInd)
    return answer

现在,让我们开始改进:

def sort(L):
    answer = []
    while L:
        minInd = 0
        min = L[0]
        for i,num in enumerate(L):
            if num<min:
                minInd = i
                min = num
        answer.append(min)
        L.pop(minInd)
    return answer

再次:

def sort(L):
    answer = []
    while L:
        m = min(L)  # using the built-in `min` function
        L.remove(m)
        answer.append(m)
    return answer