Skip to content

Instantly share code, notes, and snippets.

@reillyeon
Created March 24, 2014 05:06
Show Gist options
  • Save reillyeon/9734448 to your computer and use it in GitHub Desktop.
Save reillyeon/9734448 to your computer and use it in GitHub Desktop.
Merge sort.
def mergesort(a):
if len(a) <= 1:
return
mid = len(a) // 2
b = a[:mid]
mergesort(b)
c = a[mid:]
mergesort(c)
i, j, k = 0, 0, 0
while j < len(b) and k < len(c):
if b[j] < c[k]:
a[i] = b[j]
j += 1
else:
a[i] = c[k]
k += 1
i += 1
while j < len(b):
a[i] = b[j]
i += 1
j += 1
while k < len(c):
a[i] = c[k]
i += 1
k += 1
if __name__ == '__main__':
import random
a = [random.randint(0, 1000) for i in range(100)]
print(a)
mergesort(a)
print(a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment