I am trying to create a method for merge sort recursively. I am not so familiar with objects and i am trying to get this right. I know the algorithm works as a stand alone function, but when trying to implement as a class method, i get error.
The problem lies in this two lines of code:
left_list = left_list.merge_sort()
right_list = right_list.merge_sort()
class Lists(object):
def __init__(self):
self.capacity = 8
self.arr = [None] * capacity
self.size = 0
def merge_sort(self):
if self.size <= 1:
return self.arr
middle = self.size // 2
left_list = self.arr[:middle]
right_list = self.arr[middle:]
left_list = left_list.merge_sort()
right_list = right_list.merge_sort()
return list(self.merge(left_list, right_list))
def merge(self, left_half, right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
And of course is another function append, that appends each time at the self.arr and increases the size by 1 each time an element is appended.