简体   繁体   中英

Merge Sort Using Python

I didn't get the sorted list, instead only one value.

def merge1(left,right):
    print("left" , left , "right" , right)
    def loop(left,right,ss):
        print("left" , left , "right" , right)
        if not (left ==[] or right ==[]):
            if left[0] <= right[0]:
                ss.append(left[0]) 
                return loop(left[1:],right, ss)
            else:
                ss.append(right[0])
                return loop(left,right[1:], ss)
            print("hello")
        else:
            return ss
    return loop(left,right,[])


def msort(s):
    if len(s)>1:
        mid = len(s) // 2
        return merge1(msort(s[:mid]),msort(s[mid:]))
    else:
        return s

print(msort([9,8,7,6,5,4,3,2,1]))

You are not addressing the case where either one of the left or right array is exhausted. You will have to copy the remaining values from the non-empty array to the merged array:

def merge1(left,right):
    print("left" , left , "right" , right)
    def loop(left,right,ss):
        print("left" , left , "right" , right)
        if left and right:
            if left[0] <= right[0]:
                ss.append(left[0]) 
                return loop(left[1:],right, ss)
            else:
                ss.append(right[0])
                return loop(left,right[1:], ss)
        # either one of left or right is empty so you need to copy the remaining
        # values into merged array
        else:
            if left:
                for i in left:
                    ss.append(i)
            if right:
                for i in right:
                    ss.append(i)
            print ss
            return ss
    return loop(left,right,[])


def msort(s):
    if len(s)>1:
        mid = len(s) / 2
        return merge1(msort(s[:mid]),msort(s[mid:]))
    else:
        return s

print(msort([9,8,7,6,5,4,3,2,1]))

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