There are numerous implementations of merge sort I've seen, however, I'm trying to write one which translates literally from the algorithmic definition of merge sort:
- Split the arrays till you've 1 element left
- Merge them together.
However I'm a little stuck. This is my code till now,
class MergeSort:
def __init__(self):
bucket = []
def _sort(self, arr):
if len(arr) == 1:
pass
mid = len(arr) //2
self._sort(arr[:mid])
self._sort(arr[mid:])
def _merge(self, arr1, arr2, arr):
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
arr.append(arr1[i])
i += 1
else:
arr.append(arr2[j])
j += 1
The code will be called in this manner.
merge_sort = MergeSort()
merge_sort._sort([1,9,3,2,5])
Can someone help me stitch these two methods together to get the merge sort someway. Just to reiterate I'm not looking at a new approach. Thanks.
bucketetc.. Where's the code that uses this class?_sort()method using your class, you don't need to initialize with abucketvariable.Split the arrays till you've 1 element left- note this could be done in one step by considering an array of n elements as n sub-arrays of 1 element each, then using iteration to update indices and merge those sub-arrays. This would be a "bottom up" merge sort.