Merge sort wrong output

hi sir/maam i m trying to code merge sort in python but got wrong ans can u plz find mistakes in my code

Hey @Ashu1318, I checked your code thoroughly, and there were quite a few mistakes. t had to be a local variable inside the function because everytime merge function was called the elements were getting appended in t (which was not making sense). I have corrected this and a few other things also I had to change due to this change. Kindly refer the corrected code :

 
def merge(a,s,e,mid):
    i=s
    j=mid+1
    k=0
    t=[]
    while(i<=mid and j<=e):
        if a[i]<a[j]:
           t.append(a[i])
           i=i+1
           k=k+1
        else:
            t.append(a[j])
            j=j+1
            k=k+1    
    while(i<=mid):
         t.append(a[i])
         i=i+1
         k=k+1 
    while(j<=e):
        t.append(a[j])
        j=j+1
        k=k+1  

    m=0
    i=s
    while(i<=e):
        a[i]=t[m]
        m += 1
        i += 1
     
def mergesort(a,s,e):
    if(s>=e):
        return 
    mid=(s+e)//2
    mergesort(a,s,mid)
    mergesort(a,mid+1,e)
    merge(a,s,e,mid)    
n=int(input())
a=[]
a = [int(n) for n in input().split()]
mergesort(a,0,n-1)
for i in range(0,n):
    print(a[i],end=' ')    

I hope this helps ! :slightly_smiling_face:
Happy Learning ! :+1:

okay now its working fine thanks

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.