Last active
August 29, 2015 14:01
-
-
Save JeremieGomez/14fc459e5a979e0f7511 to your computer and use it in GitHub Desktop.
Simple implementation of merge sort in Python (and time comparison with built-in sort)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
def mergesort(arr,length): | |
if length == 1: | |
return arr | |
else: | |
cut = length/2 | |
left = mergesort(arr[:cut],len(arr[:cut])) | |
right = mergesort(arr[cut:],len(arr[cut:])) | |
return merge(left,right, length) | |
def merge(left, right, length): | |
i = j = 0 | |
out = [None] * length | |
right_len = len(right) | |
left_len = len(left) | |
for k in range(length): | |
if j >= right_len or (i < left_len and left[i] < right[j]): | |
out[k] = left[i] | |
i += 1 | |
else: | |
out[k] = right[j] | |
j += 1 | |
return out | |
if (__name__ == '__main__'): | |
import random | |
import timeit | |
# One example to visually check that sorting works | |
arr = [4,9,2,1,23,4,12,84,3,5,25,33,1,345,2,4,7] | |
print('Not sorted : %s' % arr) | |
print('Sorted : %s' % mergesort(arr, len(arr))) | |
# Comparison between this merge sort and the built-in Python sort | |
big_arr = [random.random() for _ in range(10000)] | |
t1 = timeit.Timer(lambda: mergesort(big_arr, len(big_arr))).timeit(number=1) | |
t2 = timeit.Timer(lambda: sorted(big_arr)).timeit(number=1) | |
print('Time to sort 10000 floats with mergesort : %f seconds' % t1) | |
print('Time to sort 10000 floats with python built-in sort : %f seconds' % t2) | |
print('Ratio : %f' % (t1/t2)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Without any optimization as it is, the built-in Python sort is usually about 25 times faster.