当列表排序时,如何在冒泡排序代码中停止递归?

时间:2018-01-20 17:36:16

标签: python sorting recursion

问题:在python中实现冒泡排序。不要使用Python的内置排序或排序。假设您的输入足以满足您的记忆。

代码:

def check_if_sorted(details):
    """compares two consecutive integers in a list and returns the list if sorted else get the list sorted by calling another function"""
    i = 0
    while i <=  len(details) - 2:
        if details[i] < details[i+1]:
            status = True
            i = i+1
            print details
        else:
            bubble_sort(details)
    if status :
        return details


def bubble_sort(details):  
    """compares two consecutive integers in a list and shifts the smaller one to left """
    for i in range(len(details)-1):
        if details[i] > details[i+1]:
            temp = details[i]
            details[i]= details[i+1]
            details[i+1] = temp
    return check_if_sorted(details)


sort_me = [11,127,56,2,1,5,7,9,11,65,12,24,76,87,123,65,8,32,86,123,67,1,67,92,72,39,49,12, 98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,97,0,63,25,85,24,94,1501]
print sort_me 
print bubble_sort(sort_me)

我编写了以下代码,但即使在对列表进行排序后也会继续运行,然后打印出“运行错误:调用Python对象时超出最大递归深度”的消息。检查列表是否已排序后,如何停止递归?

2 个答案:

答案 0 :(得分:1)

您不需要check_if_sorted(details)功能。在排序函数中使用try/except来检查IndexError并继续调用bubble_sort()函数。

def bubble_sort(details):  
    """compares two consecutive integers in a list and shifts the smaller one to left """
    for i in range(len(details)-1):
        try:
            if details[i] > details[i+1]:
                temp = details[i]
                details[i]= details[i+1]
                details[i+1] = temp
                bubble_sort(details)
        except IndexError:
            return
    return details


sort_me = [11,127,56,2,1,5,7,9,11,65,12,24,76,87,123,65,8,32,86,123,67,1,67,92,72,39,49,12, 98,52,45,19,37,22,1,66,943,415,21,785,12,698,26,36,18,97,0,63,25,85,24,94,1501]
print(sort_me)
print(bubble_sort(sort_me))

答案 1 :(得分:1)

check_if_sorted中,您不会检查是否相同。这会导致列表中的重复项触发另一个(不需要的)调用bubble_sort,从而导致无限循环。要解决此问题,请将check_if_sorted中的比较行更改为:

        if details[i] <= details[i+1]:

编辑: 这解决了无限循环,但是你的算法非常低效。为了改进您的算法,我建议谷歌搜索“冒泡排序算法”,和/或与教师讨论