[Python] MergeSort without merge function,, How does this algorithm merges the lists

Discussão em 'Python' iniciado por Stack, Agosto 30, 2025.

  1. Stack

    Stack Membro Participativo

    def mergeSort(A):
    if len(A) < 2:
    return A

    mid = int(len(A)/2)
    left = mergeSort(A[:mid])
    right = mergeSort(A[mid:])

    r,l = 0,0
    B = []

    while len(B) < len(A):
    if r >= len(right) or (l < mid and left[l] < right[r]):
    B.append(left[l])
    l += 1
    elif r < len(right):
    B.append(right[r])
    r += 1

    return B

    print(mergeSort([4,3,6,9,8,5,1]))


    My doubt in the above program is how the lists are merged without a separate merge function?

    After the recursive function calls in the end I think left and right lists contain only one element each... they are sorted and inserted in to list B using a while loop... what about other elements.. because here while loop is executed only once and how the list A is again split and merged...I got this program in internet and it works perfectly fine.

    Continue reading...

Compartilhe esta Página