Merge Sort: The Algorithm

This is it. The last time I wrote about Merge Sort was last night last week and now I will show you the fun.

So here’s the code I’ve written in 9 minutes 42 seconds (almost 10 minutes!) straight.

from random import randint

def sample_list(n, r):
    result = []
    for c in range(0, n):
        result.append(randint(0, r))

    return result

def merge(left, right):
    i, j = 0, 0

    result = []

    while i < len(left) and j < len(right):
        if left[i] <= right[j]:
            result.append(left[i])
            i += 1
        else:
            j += 1

    if i < len(left):
        result += left[i:]

    if j < len(right):
        result += right[j:]

    return result

def sort(mylist):
    if len(mylist) < 2:
        return mylist

    midlist = len(mylist) / 2
    left_list = mylist[:midlist]
    right_list = mylist[midlist:]

    left_list, right_list = sort(left_list), sort(right_list)
    return merge(left_list, right_list)

if __name__ == '__main__':
    l = sample_list(10, 1000)
    print 'Unsorted list'
    print l
    print '\nSorted list'
    sort(l)

Pretty easy, right? Let me know if you have any comments or questions!

Also read...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.