[Python] Explanation of Merge Sort for Dummies

Discussão em 'Python' iniciado por Stack, Abril 20, 2025.

  1. Stack

    Stack Membro Participativo

    I found this code online:

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

    def mergesort(list):
    if len(list) < 2:
    return list
    middle = len(list) / 2
    left = mergesort(list[:middle])
    right = mergesort(list[middle:])
    return merge(left, right)


    It works 100% when I run it. I just do not really get how the merge sort works or how the recursive function is able to properly order both a left and a right.

    Continue reading...

Compartilhe esta Página