2020-05-24 06:38:43 +00:00
|
|
|
def merge(arr, left, mid, right):
|
|
|
|
# overall array will divided into 2 array
|
|
|
|
# left_arr contains the left portion of array from left to mid
|
|
|
|
# right_arr contains the right portion of array from mid + 1 to right
|
|
|
|
left_arr = arr[left : mid + 1]
|
|
|
|
right_arr = arr[mid + 1 : right + 1]
|
|
|
|
k = left
|
2019-10-22 17:13:48 +00:00
|
|
|
i = 0
|
|
|
|
j = 0
|
2020-05-24 06:38:43 +00:00
|
|
|
while i < len(left_arr) and j < len(right_arr):
|
2019-10-22 17:13:48 +00:00
|
|
|
# change sign for Descending order
|
2020-05-24 06:38:43 +00:00
|
|
|
if left_arr[i] < right_arr[j]:
|
|
|
|
arr[k] = left_arr[i]
|
2019-10-22 17:13:48 +00:00
|
|
|
i += 1
|
2019-10-09 19:12:09 +00:00
|
|
|
else:
|
2020-05-24 06:38:43 +00:00
|
|
|
arr[k] = right_arr[j]
|
2019-10-22 17:13:48 +00:00
|
|
|
j += 1
|
|
|
|
k += 1
|
2020-05-24 06:38:43 +00:00
|
|
|
while i < len(left_arr):
|
|
|
|
arr[k] = left_arr[i]
|
2019-10-22 17:13:48 +00:00
|
|
|
i += 1
|
|
|
|
k += 1
|
2020-05-24 06:38:43 +00:00
|
|
|
while j < len(right_arr):
|
|
|
|
arr[k] = right_arr[j]
|
2019-10-22 17:13:48 +00:00
|
|
|
j += 1
|
|
|
|
k += 1
|
2020-05-24 06:38:43 +00:00
|
|
|
return arr
|
2019-10-22 17:13:48 +00:00
|
|
|
|
|
|
|
|
2020-05-24 06:38:43 +00:00
|
|
|
def mergesort(arr, left, right):
|
2019-10-09 19:12:09 +00:00
|
|
|
"""
|
2020-05-24 06:38:43 +00:00
|
|
|
>>> mergesort([3, 2, 1], 0, 2)
|
2019-10-09 19:12:09 +00:00
|
|
|
[1, 2, 3]
|
2020-05-24 06:38:43 +00:00
|
|
|
>>> mergesort([3, 2, 1, 0, 1, 2, 3, 5, 4], 0, 8)
|
2019-10-09 19:12:09 +00:00
|
|
|
[0, 1, 1, 2, 2, 3, 3, 4, 5]
|
|
|
|
"""
|
2020-05-24 06:38:43 +00:00
|
|
|
if left < right:
|
|
|
|
mid = (left + right) // 2
|
2019-10-22 17:13:48 +00:00
|
|
|
# print("ms1",a,b,m)
|
2020-05-24 06:38:43 +00:00
|
|
|
mergesort(arr, left, mid)
|
2019-10-22 17:13:48 +00:00
|
|
|
# print("ms2",a,m+1,e)
|
2020-05-24 06:38:43 +00:00
|
|
|
mergesort(arr, mid + 1, right)
|
2019-10-22 17:13:48 +00:00
|
|
|
# print("m",a,b,m,e)
|
2020-05-24 06:38:43 +00:00
|
|
|
merge(arr, left, mid, right)
|
|
|
|
return arr
|
2019-10-09 19:12:09 +00:00
|
|
|
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2019-10-09 19:12:09 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
import doctest
|
2019-10-22 17:13:48 +00:00
|
|
|
|
2019-10-09 19:12:09 +00:00
|
|
|
doctest.testmod()
|