【问题标题】:How to stop recursion in my bubble sort code when the list is sorted?列表排序后如何停止冒泡排序代码中的递归?
【发布时间】:2018-05-17 20:23:03
【问题描述】:

问题:在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)

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

【问题讨论】:

    标签: python sorting recursion


    【解决方案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))
    

    【讨论】:

      【解决方案2】:

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

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

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

      【讨论】:

      • 解决了无限循环的问题,但是代码在整个列表排序后并没有立即停止
      猜你喜欢
      • 2013-10-09
      • 1970-01-01
      • 2012-05-28
      • 1970-01-01
      • 2011-12-09
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-22
      相关资源
      最近更新 更多