class mergeSort:
def __init__(self, arr):
self.arr = arr
def sort(self, low, high):
if not self.arr:
return(self.arr)
if low >= high:
return([self.arr[low]])
mid = low + (high - low) // 2
arr1 = self.sort(low, mid)
arr2 = self.sort(mid + 1, high)
arr3 = self.merge(arr1, arr2)
return(arr3)
def merge(self, arr1, arr2):
if(len(arr1) == 0):
return(arr2)
if(len(arr2) == 0):
return(arr1)
oneIdx = 0
twoIdx = 0
resp = []
while oneIdx < len(arr1) or twoIdx < len(arr2):
if oneIdx < len(arr1) and twoIdx < len(arr2):
if arr1[oneIdx] <= arr2[twoIdx]:
resp.append(arr1[oneIdx])
oneIdx += 1
else:
resp.append(arr2[twoIdx])
twoIdx += 1
elif oneIdx < len(arr1):
resp.append(arr1[oneIdx])
oneIdx += 1
else:
resp.append(arr2[twoIdx])
twoIdx += 1
return(resp)
if __name__ == "__main__":
arr = [4,2,7,1,9,0]
test = mergeSort(arr)
assert(test.sort(0, len(arr) - 1) == [0,1,2,4,7,9])
print(test.sort(0, len(arr) - 1))
arr = [4,2,7,-1,9,0]
test = mergeSort(arr)
assert(test.sort(0, len(arr) - 1) == [-1,0,2,4,7,9])
print(test.sort(0, len(arr) - 1))
arr = [0]
test = mergeSort(arr)
assert(test.sort(0, len(arr) - 1) == [0])
print(test.sort(0, len(arr) - 1))
arr = []
test = mergeSort(arr)
assert(test.sort(0, len(arr) - 1) == [])
print(test.sort(0, len(arr) - 1))