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

2024-06-01 06:30:32 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:在python中实现冒泡排序。不要使用Python内置的sort或sorted。假设你的输入足够你的内存。在

代码:

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)

我已经编写了以下代码,但它仍然在运行,即使在对列表排序之后,它也会继续运行,然后打印消息“RuntimeError:maximum recursion depth exceeded when calling a Python object”。如何在检查列表排序后停止递归?在


Tags: the代码inifdefcheckdetailssort
2条回答

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

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

编辑: 这解决了无限循环,但是您的算法效率很低。为了改进你的算法,我建议你在谷歌上搜索“气泡排序算法”,或者和你的导师讨论一下

您不需要check_if_sorted(details)函数。在sort函数中使用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))

相关问题 更多 >