I wrote the code for mergeSort
from here from memory after reading it. I made the mistake of not indenting after the if
statement and not including the recursive calls of mergeSort
. I got the same unsorted array [54, 26, 77, 31, 44, 55, 20, 93, 17]
with no errors from the interpreter.
I looked back at the reference and then realized I didn't make the recursive calls (commented out in the code below). I included them and got this error:
UnboundLocalError: local variable 'leftHalf' referenced before assignment
I don't get why this wasn't an issue before calling mergeSort
recursively. I also thought that Python wasn't like C++ where variables in if
statements could be referenced outside.
I know that everything after the if
statement should be indented for this to be correct but would like to understand Python after bumping into this.
def mergeSort(alist):
if len(alist) > 1:
mid = len(alist) // 2 # pick shorter end as left
leftHalf = alist[:mid]
rightHalf = alist[mid:]
# 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 += 1
else:
alist[k] = rightHalf[j]
j += 1
k += 1
# right side was all smaller and is done. Fill all left
while i < len(leftHalf):
alist[k] = leftHalf[i]
i += 1
k += 1
# left side was all smaller and is done. Fill all right
while j < len(rightHalf):
alist[k] = rightHalf[j]
i += 1
k += 1
alist = [54,26,93,17,77,31,44,55,20]
mergeSort(alist)
print(alist)
I looked at question 1 and question 2 and couldn't figure out how similar my case is to those in the question because I didn't define a new function.