使用递归在Python中合并排序代码

时间:2014-02-18 06:09:20

标签: python recursion mergesort

下面是用Python编写的合并排序。它抛出错误“RuntimeError:超出最大递归深度”。如果我错过了结束递归的逻辑,请告诉我。

  list=[]
  list1=[]
  list2=[]
  def merge(list,list1,list2):

  for k in range(1,len(list1)+len(list2)):
    i=1
    j=1
    if list1[i]>list2[j]:
        list[k]=list2[j]
        j=+1
        k=+1
    else:
        list[k]=list2[i]
        i=+1
        k=+1


    def split(list,list1,list2):
if len(list)<>1:
    list1=list[:len(list)/2]
    list2=list[len(list)/2:]
return  


   def sort(list):
      split(list,list1,list2)
      sort(list1)
      sort(list2)
      merge(list,list1,list2)


      list = [15,8,59,69,45,23]
      sort(list)

2 个答案:

答案 0 :(得分:2)

试试这个程序:

 def sort( aList ):
      aList = _mergesort( aList, 0, len( aList ) - 1 )
      return aList

def _mergesort( aList, first, last ):
  mid = ( first + last ) / 2
  if first < last:
    _mergesort( aList, first, mid )
    _mergesort( aList, mid + 1, last )

  a, f, l = 0, first, mid + 1
  tmp = [None] * ( last - first + 1 )

  while f <= mid and l <= last:
    if aList[f] < aList[l] :
      tmp[a] = aList[f]
      f += 1
    else:
      tmp[a] = aList[l]
      l += 1
    a += 1

  if f <= mid :
    tmp[a:] = aList[f:mid + 1]

  if l <= last:
    tmp[a:] = aList[l:last + 1]

  a = 0
  while first <= last:
    aList[first] = tmp[a]
    first += 1
    a += 1
  return aList

aList = [15,8,59,69,45,23]
print sort(aList)

答案 1 :(得分:1)

避免在此脚本中进行全局变量初始化

>>> x = 5
>>> def show2():
...     x = 42
...     print x
... 
>>> show2()
42
>>> x
5

问题是你用相同的参数递归调用自己,这保证了无限递归。设置递归限制有多高并不重要;你无法将它设置为无限远。*