0

In the below example what exactly is happening inside the function that is called inside of itself?
What is being output at what point of the function? Is there something analogous to what is happening here that can be rewritten in a simple way?

def mergeSort(myList):
    if len(myList) > 1:
        mid = len(myList) // 2
        left = myList[:mid]
        right = myList[mid:]

        # Recursive call on each half
        mergeSort(left)
        mergeSort(right)

        # Two iterators for traversing the two halves
        i = 0
        j = 0

        # Iterator for the main list
        k = 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
              # The value from the left half has been used
              myList[k] = left[i]
              # Move the iterator forward
              i += 1
            else:
                myList[k] = right[j]
                j += 1
            # Move to the next slot
            k += 1

        # For all the remaining values
        while i < len(left):
            myList[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            myList[k]=right[j]
            j += 1
            k += 1

myList = [54,26,93,17,77,31,44,55,20]
mergeSort(myList)
print(myList)
grissler
  • 1
  • 2
  • It works *exactly* the same way as calling any other function. – juanpa.arrivillaga Dec 10 '20 at 20:16
  • 1
    Do you know about the term [Recursion](https://en.wikipedia.org/wiki/Recursion_(computer_science))? Also, Python has a [recursion limit](https://stackoverflow.com/questions/3323001/what-is-the-maximum-recursion-depth-in-python-and-how-to-increase-it) which you can change if needed. There's a ton of info online on how recursion works, I found a lot just by searching "function in code that calls itself". Usually it's good to research before posting here since a lot of questions have already been answered to some degree. – Random Davis Dec 10 '20 at 20:16
  • I did searches but with the word 'Python' and I just got results for calling functions inside functions. Did you mark duplicate? I guess I can learn about it now that I know it has a name but I've heard the CEO of StackOverflow interviewed saying a duplicate question with a differently worded title is not a duplicate, plus I was interested in what's happening in this specific case. – grissler Dec 10 '20 at 20:34

0 Answers0