Skip to content

Instantly share code, notes, and snippets.

@SamuraiT
Created January 11, 2015 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SamuraiT/3d99232a84fe7acbd77a to your computer and use it in GitHub Desktop.
Save SamuraiT/3d99232a84fe7acbd77a to your computer and use it in GitHub Desktop.
#! /usr/bin/env python
# coding: utf-8
"""
Copyright 2014 Tatsuro Yasukawa.
Distributed under the GNU General Public License at
gnu.org/licenses/gpl.html.
"""
def merge(x,y):
"""
>>> x,y = [2],[5]
>>> merge(x,y)
[2, 5]
>>> x = [2, 5]
>>> y = [4, 6]
>>> merge(x,y)
[2, 4, 5, 6]
"""
i = j = 0
t = []
while i < len(x) and j < len(y):
if x[i] < y[j]:
t.append(x[i])
i += 1
else:
t.append(y[j])
j += 1
if not i < len(x):
t.extend(y[j:])
else:
t.extend(x[i:])
return t
def merge_sort(t):
"""
>>> t = [3,5,6,9,4,6,7,8,2,9,1,2]
>>> merge_sort(t)
[1, 2, 2, 3, 4, 5, 6, 6, 7, 8, 9, 9]
"""
if len(t) < 2: return t
i = len(t)/2
return merge(
merge_sort(t[:i]),
merge_sort(t[i:])
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment