Skip to content

Instantly share code, notes, and snippets.

@sr6033
Last active February 18, 2020 11:11
Show Gist options
  • Select an option

  • Save sr6033/1592d3c19b7bc4d2dcf892f20f5a50ac to your computer and use it in GitHub Desktop.

Select an option

Save sr6033/1592d3c19b7bc4d2dcf892f20f5a50ac to your computer and use it in GitHub Desktop.
MergeSort using python
def merge(arr, l, m, r):
n1 = m-l+1
n2 = r-m
L = []
R = []
for i in range(0, n1):
L.append(arr[l+i])
for i in range(0, n2):
R.append(arr[m+1+i])
i, j, k = 0, 0, l
while i<n1 and j<n2:
if L[i] <= R[j]:
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i < n1:
arr[k] = L[i]
i += 1
k += 1
while j < n2:
arr[k] = R[j]
j += 1
k += 1
def mergesort(arr, l, r):
if l < r:
mid = l + (r-l)//2
mergesort(arr, l, mid)
mergesort(arr, mid+1, r)
merge(arr, l, mid, r)
return arr
mergesort([12, 11, 13, 5, 6, 7], 0, 5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment