冒泡排序不返回列表

时间:2016-05-10 11:55:50

标签: python

我已经编写了这个冒泡排序程序,当我运行它时,控制台会打印'返回'但是列表没有返回,我不明白为什么。

def bub_sort(ol):
    print'function start'
    s=0
    for x in range(1,len(ol)):
        print'in floop'
        if ol[x]>ol[x-1]:
            print'swap'
            ol[x],ol[x-1]=ol[x-1],ol[x]
            s=s+1
    if s>0:
        print'restart'
        bub_sort(ol)
    else:
        print'return'
        return ol

收到一条消息说我的问题重复,另一个问题忘了回来。

1 个答案:

答案 0 :(得分:4)

你没有从递归电话中返回。

def bub_sort(ol):
    print 'function start'
    s = 0
    for x in range(1, len(ol)):
        print 'in floop'
        if ol[x] > ol[x-1]:
            print 'swap'
            ol[x], ol[x-1] = ol[x-1], ol[x]
            s += 1  # Python has the increment operator. 
    if s > 0:
        print 'restart'
        return bub_sort(ol)
    else:
        print 'return'
        return ol

P.S。 在冒泡排序中不需要递归。

相关问题