Python Merge Algorithm -


this seems working now... open criticism welcome. ty tsroten.

debug = 1 #list merged a=[1,2,3,4,5,6,1,2,3,4,5,6,7]  #artificial variables calling function p=0 r=len(a) q=int(((p+r)/2)-1)  #list append merged values b=[]  #end of list end=len(a)  if debug:     print ('mid: %d\n' % (q))     print ('end: %d' % (end))  #left , right lists sentinels l=a[:q+1] r=a[q+1:] l.append(none) r.append(none)  #init counters i=k=j=l=0  if debug:     print ('a:%s' %(a))     print ('\n')     print ('l:%s' %(l))     print ('r:%s' %(r))     print ('\n')  #merge left , right lists k in a:     if debug:         print ('iteration:%d' % (l))         l+=1         print ('i=%d, j=%d' % (i, j))         print ('b:%s' %(b))         print ('\n')     if l[i] not none , l[i]<=r[j]:         b.append(l[i])         i+=1     else:         b.append(r[j])         j+=1  print ('result:',b) 

i trying write merge algorithm in python keep running error.

traceback (most recent call last):   file "c:/python34/scripts/mergesort.py", line 19, in <module>     if l[i]<=r[j] , i<mid: indexerror: list index out of range 

i have looked @ other algorithms don't seem have same problem. please help.

a=[2,4,5,7,1,3,7,8,9]   b=[]   end=len(a)   mid=int(end/2)  l=a[:mid]   r=a[mid+1:]  i=k=j=0  k in a:       if l[i]<=r[j] , i<mid:           b.append(l[i])           i+=1       elif j<end:           b.append(r[j])           j+=1    print (b) 

your for loop goes through items in a, longer l or r. so, @ point, i , j become greater length of l , r. @ point, referencing l[i] or r[j] raises indexerror.


Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -