I am trying to make merge sort work within a class "Sorter for a python project, using the first code. The problem is that whenever I initialize the code, it calls the error "merge_sort' is not defined", and if I remove the "merge_sort" and use "left = lst[:mid]", it only cuts the list into half & reorganizes, but doesn't complete the script with the whole list. Is there a way to get around this issue? Thanks!!
from sorter import Sorter
unsorted_list = [5, -3, 4, 10, -14, 2, 4, -5]
my_sorter = Sorter()
my_sorter.unsorted_tuple = tuple(unsorted_list)
sorted_list = my_sorter._merge_sort()
print(sorted_list)
My code:
class Sorter():
def __init__(self):
self.unsorted_tuple = tuple([])
self.algorithm = 'default'
def generate_new_tuple(self, n):
new_list = []
for x in range (0, n):
new_list.append(random.randint(0, maxsize))
tuple(new_list)
self.unsorted_tuple = new_list
return None
def _merge_sort(self, reverse=False):
lst = list(self.unsorted_tuple)
result = []
i,j = 0,0
if(len(lst)<= 1):
return lst
mid = int(len(lst)/2)
left = _merge_sort(lst[:mid])
right = _merge_sort(lst[mid:])
while i<len(left) and j<len(right):
if left[i] <= right[j]:
result.append(left[i])
i+=1
else:
result.append(right[j])
j+=1
result += left[i:]
result += right[j:]
return result