Domanda

Below is intended for a merge sort written in Python. It is throwing an error "RuntimeError: maximum recursion depth exceeded". Please let me know if I am missing the logic to end the recursion.

  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)
È stato utile?

Soluzione

Try this program:

 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)

Altri suggerimenti

Avoid global variable initialization in this script

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

The problem is that you recursively call yourself with the same parameters, which guarantees infinite recursion. It doesn't matter how high you set the recursion limit; you can't set it past infinity.*

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top