Merge sort Update variable names (#2032)

* Update Merge sort variable names

* Update mergesort.py

* Update mergesort.py

* black

* Update mergesort.py

Co-authored-by: Christian Clauss <cclauss@me.com>
This commit is contained in:
Ekansh Mangal 2020-05-24 12:08:43 +05:30 committed by GitHub
parent d8a4faf96d
commit 025b1a6989
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,45 +1,48 @@
def merge(a, b, m, e): def merge(arr, left, mid, right):
l = a[b : m + 1] # noqa: E741 # overall array will divided into 2 array
r = a[m + 1 : e + 1] # left_arr contains the left portion of array from left to mid
k = b # 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
i = 0 i = 0
j = 0 j = 0
while i < len(l) and j < len(r): while i < len(left_arr) and j < len(right_arr):
# change sign for Descending order # change sign for Descending order
if l[i] < r[j]: if left_arr[i] < right_arr[j]:
a[k] = l[i] arr[k] = left_arr[i]
i += 1 i += 1
else: else:
a[k] = r[j] arr[k] = right_arr[j]
j += 1 j += 1
k += 1 k += 1
while i < len(l): while i < len(left_arr):
a[k] = l[i] arr[k] = left_arr[i]
i += 1 i += 1
k += 1 k += 1
while j < len(r): while j < len(right_arr):
a[k] = r[j] arr[k] = right_arr[j]
j += 1 j += 1
k += 1 k += 1
return a return arr
def mergesort(a, b, e): def mergesort(arr, left, right):
""" """
>>> mergesort([3,2,1],0,2) >>> mergesort([3, 2, 1], 0, 2)
[1, 2, 3] [1, 2, 3]
>>> mergesort([3,2,1,0,1,2,3,5,4],0,8) >>> mergesort([3, 2, 1, 0, 1, 2, 3, 5, 4], 0, 8)
[0, 1, 1, 2, 2, 3, 3, 4, 5] [0, 1, 1, 2, 2, 3, 3, 4, 5]
""" """
if b < e: if left < right:
m = (b + e) // 2 mid = (left + right) // 2
# print("ms1",a,b,m) # print("ms1",a,b,m)
mergesort(a, b, m) mergesort(arr, left, mid)
# print("ms2",a,m+1,e) # print("ms2",a,m+1,e)
mergesort(a, m + 1, e) mergesort(arr, mid + 1, right)
# print("m",a,b,m,e) # print("m",a,b,m,e)
merge(a, b, m, e) merge(arr, left, mid, right)
return a return arr
if __name__ == "__main__": if __name__ == "__main__":