简体   繁体   中英

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

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.

You append the fields from a and b to c, but in the end you print a. Maybe this is the problem.

Array a is never edited

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM