Search code examples
pythonpython-3.xmergesort

Implementing merge sort in python3


I don't know what's wrong here. can anyone help me do merge sort in python3.Please ,where did i go wrong....?

def merge_help(a,b):
    c=[]
    j=0
    i=0
    while(i<len(a) and j<len(b)):
        if(a[i]>=b[j]):
            c.append(b[j])
            j+=1
        elif(a[i]<=b[j]):
            c.append(a[i])
            i+=1
    while(j<len(b)):
        c.append(b[j])
        j+=1
    while(i<len(a)):
        c.append(a[i])
        i+=1
    return c
    def merge(a):
    if(len(a)>1):
        mid =len(a)//2
        l=a[:mid]
        r=a[mid:]
        merge(l)
        merge(r)
        merge_help(l,r)
    print(a)

merge([12,11,13,5,6,7]) doesn't work.... no errors but same list is returned back every recursive step


Solution

  • You are not capturing the output of merge_help, so you are not actually changing the values in the 'a' list.

    You are also attempting to do this in-place, which is not possible with merge sort.

    In your merge function, do this:

    def merge(a):
        if(len(a) > 1):
            # Divide the list in two
            mid = len(a)//2
            left_unsorted = a[:mid]
            right_unsorted = a[mid:]
    
            # Sort both halves
            left_sorted = merge(left_unsorted)
            right_sorted = merge(right_unsorted)
    
            # Merge the two sorted lists
            a_sorted = merge_help(left_sorted, right_sorted)
        else:
            a_sorted = a.copy()
        return a_sorted
    

    Note: this does not sort the passed list; it only returns a sorted version. So if you call it with orig_list, orig_list will be unchanged at the end.