排序没有内置函数的列表,如sort,set,min,max,python中的remove

时间:2016-12-20 23:00:43

标签: python list sorting

我有一个二维列表,我必须排序,我只能使用while循环。到目前为止,我的代码并不适用于所有列表。

def sort(list):
    i = 0
    j = 0
    while i < len(list):
        while j < len(list[i]) - 1:
            if list[i][j] > list[i][j + 1]:
                temp = list[i][j]
                list[i][j] = list[i][j + 1]
                list[i][j + 1] = temp
            j += 1
        j = 0
        i += 1
    return list
sort([[3,5,2,8,6,9],[9,1,2,5]])

此代码的数字仍然无序。有更好的排序方式吗?

1 个答案:

答案 0 :(得分:2)

你的内部循环只通过列表一次。这保证了最大的元素在最后,但不一定做任何其他的。您还需要在尚未完成业务的情况下添加循环以继续。

我留下了用于强调问题的跟踪语句,以及简单的逆序案例。

def sort(list):
    i = 0
    j = 0
    while i < len(list):
        done = False
        while not done:
            done = True
            while j < len(list[i]) - 1:
                print i, j, list[i][j], list[i][j + 1]
                if list[i][j] > list[i][j + 1]:
                    temp = list[i][j]
                    list[i][j] = list[i][j + 1]
                    list[i][j + 1] = temp
                    done = False
                    print "SWAP", list[i]
                j += 1

            j = 0

        i += 1
    return list

print sort([[6, 5, 4, 3, 2, 1, 0]])
print sort([[3,5,2,8,6,9],[9,1,2,5]])
相关问题