Skip to content

Instantly share code, notes, and snippets.

@robbie01
Last active December 30, 2016 02:28
Show Gist options
  • Save robbie01/2bfad54b2cdcfef5d633425d7bcf2b7e to your computer and use it in GitHub Desktop.
Save robbie01/2bfad54b2cdcfef5d633425d7bcf2b7e to your computer and use it in GitHub Desktop.
Merge sort implemented in Python 3
def mergesort(c):
if len(c) > 1:
pivot = len(c)//2
a = c[:pivot]
b = c[pivot:]
mergesort(a)
mergesort(b)
ap = 0
bp = 0
cp = 0
while ap < len(a) and bp < len(b):
if a[ap] < b[bp]:
c[cp] = a[ap]
ap += 1
else:
c[cp] = b[bp]
bp += 1
cp += 1
while ap < len(a):
c[cp] = a[ap]
ap += 1
cp += 1
while bp < len(b):
c[cp] = b[bp]
bp += 1
cp += 1
if __name__ == "__main__":
from sys import argv
from random import shuffle
list = list(range(int(argv[1])))
shuffle(list)
mergesort(list)
print(all(list[i] <= list[i+1] for i in range(len(list)-1)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment