2

I tried to implement merge-sort in Python. Somehow this piece of code runs correctly (and pretty fast), but I don't know why: There is no return-statement in mergeSort()

from sys import stdin

def mergeSort(A):
    if len(A) > 1:
        m = int(len(A)/2)
        L = A[:m]
        R = A[m:]

        mergeSort(L)
        mergeSort(R)

        l = 0
        r = 0
        a = 0
        while l < len(L) and r < len(R):
            if L[l] < R[r]:
                A[a] = L[l]
                l += 1
            else:
                A[a] = R[r]
                r += 1
            a += 1
        while l < len(L):
            A[a] = L[l]
            l += 1
            a += 1
        while r < len(R):
            A[a] = R[r]
            r += 1
            a += 1

def main():
    A = []
    for line in stdin:
        A.append(int(line))

    mergeSort(A)
    print(A)

if __name__ == "__main__":
    main()
vegarab
  • 309
  • 1
  • 10
  • 16
    As the arrays are mutated (changed in place), there's no need to return anything. – RemcoGerlich Aug 30 '17 at 14:42
  • There is an implied **return** at the end of the function. This takes you back to the calling program. Since the function has no explicit return value, the implied **return** is sufficient. This does not affect the execution speed. – Prune Aug 30 '17 at 15:29

0 Answers0