Skip to content

Instantly share code, notes, and snippets.

@fmasanori
Created September 3, 2014 13:57
Show Gist options
  • Save fmasanori/6fcb5874bd9e992855fb to your computer and use it in GitHub Desktop.
Save fmasanori/6fcb5874bd9e992855fb to your computer and use it in GitHub Desktop.
Python Interactive Mergesort
def merge(p, q, r, v):
w = []
i, j = p, q
while i < q and j < r:
if v[i] <= v[j]:
w.append(v[i])
i += 1
else:
w.append(v[j])
j += 1
while i < q:
w.append(v[i])
i += 1
while j < r:
w.append(v[j])
j += 1
for k in range(p, r): v[k] = w[k-p]
def mergesortI(v):
n = len(v)
b = 1
while b < n:
p = 0
while p + b < n:
r = p + 2*b
if r > n: r = n
merge(p, p + b, r, v)
p = p + 2*b
b = 2*b
from random import shuffle
v = list(range(8))
shuffle(v)
print (v)
mergesortI(v)
print (v)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment