Python Forum
merge sort - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: Code sharing (https://python-forum.io/forum-5.html)
+--- Thread: merge sort (/thread-23740.html)



merge sort - rootVIII - Jan-15-2020

This one always blows my mind

def merge(left, right):
    combined, left_index, right_index = [], 0, 0
    while left_index < len(left) and right_index < len(right):
        if left[left_index] < right[right_index]:
            combined.append(left[left_index])
            left_index += 1
            continue
        combined.append(right[right_index])
        right_index += 1
    combined += left[left_index:] + right[right_index:]
    return combined


def merge_sort(current):
    if len(current) < 2:
        return current

    m = int(len(current)/2)
    return merge(merge_sort(current[:m]), merge_sort(current[m:]))


if __name__ == '__main__':
    print(merge_sort([8, 6, 3, 0, 4, 5, 3, 9, 2]))



RE: merge sort - Gribouillis - Jan-15-2020

What about this one?
from heapq import merge

def merge_sort(current):
    if len(current) < 2:
        return current
 
    m = int(len(current)/2)
    return merge(merge_sort(current[:m]), merge_sort(current[m:]))
 
 
if __name__ == '__main__':
    print(list(merge_sort([8, 6, 3, 0, 4, 5, 3, 9, 2])))
Output:
[0, 2, 3, 3, 4, 5, 6, 8, 9]



RE: merge sort - perfringo - Jan-15-2020

Just being smart-ass Smile

I like floor division more than division and converting to int:

>>> int(3/2)
1
>>> 3//2
1



RE: merge sort - rootVIII - Jan-16-2020

Hmmm investigating heapq

EDIT: Yup Gribouillis you always know all the good modules hahaha


RE: merge sort - Gribouillis - Jan-16-2020

rootVIII Wrote:EDIT: Yup Gribouillis you always know all the good modules hahaha
In fact the same thing happened to me a long time ago. I wrote a clever merge() function in a forum and then I discovered that the standard library has a merge() function since version 2.6. That's how one learns the libraries the hard way!