dimanche 1 décembre 2019

How does this IF-Conditions in Python work?

This is a Mergesort i found online and tried to implement. It worked but i am not sure how it works. Can someone please explain to me why/how this if-condition works? Where does the code continue when the first-if statement isnt true anymore. I know how if-condtions work in general but to the lack of indentions and/or 'else' confuses me here.

def mergeSort(alist):
   print("Splitting ",alist)
   if len(alist)>1:
       mid = len(alist)//2
       lefthalf = alist[:mid]
       righthalf = alist[mid:]
       #recursion
       mergeSort(lefthalf)
       mergeSort(righthalf)

       i=0
       j=0
       k=0

       while i < len(lefthalf) and j < len(righthalf):
           if lefthalf[i] < righthalf[j]:
               alist[k]=lefthalf[i]
               i=i+1
           else:
               alist[k]=righthalf[j]
               j=j+1
           k=k+1

       while i < len(lefthalf):
           alist[k]=lefthalf[i]
           i=i+1
           k=k+1

       while j < len(righthalf):
           alist[k]=righthalf[j]
           j=j+1
           k=k+1

alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)```

Aucun commentaire:

Enregistrer un commentaire