0

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]))
2
  • I suggest you compare to this implementation: interactivepython.org/courselib/static/pythonds/SortSearch/… Commented Oct 8, 2015 at 18:16
  • Try using a simpler example. For example, what should merge1([1], [2]) return, and what does it actually return? What about merge1([1], [])? Commented Oct 8, 2015 at 18:17

1 Answer 1

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]))
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, meaning that if left or right becomes exhausted, it will still be in the merged array?
yes, say you are merging two lists where one is empty([1, 2, 3], []) you need to return [1, 2, 3] as the merged array, in your original code this was not implemented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.