Thursday, July 11, 2013

Mergesort in Python

My train was cancelled today and as I am trying to cement my knowledge of python  I decided to do mergesort in python from memory. I find when adding new languages to my toolkit It is easy to forget how to setup a quick project with unit tests so I find it useful to do regular little projects from scratch Here's the code:

class MergeSort(object):
@staticmethod
def sort(array):
if len(array) <= 1:
return array
else:
middle = len(array)/2
left_half = MergeSort.sort(array[:middle])
right_half = MergeSort.sort(array[middle:])
merged = []
i,j,= 0,0
while (i + j) < (len(left_half) + len(right_half)):
if i < len(left_half) and j < len(right_half):
if left_half[i] < right_half[j]:
merged.append(left_half[i])
i += 1
else:
merged.append(right_half[j])
j += 1
elif i < len(left_half):
merged.append(left_half[i])
i += 1
elif j < len(right_half):
merged.append(right_half[j])
j += 1
return merged
view raw mergesort.py hosted with ❤ by GitHub

 And hear's the unit tests (of course the unit tests came first!):

import unittest
from mergesort import MergeSort
class MergeSortTest(unittest.TestCase):
def setUp(self):
self.under_test = MergeSort()
def test_empty_array(self):
array_to_sort = []
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([], array_to_sort)
def test_single_element(self):
array_to_sort = [1]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1], sorted_array)
def test_two_elements_sorted(self):
array_to_sort = [1, 2]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1, 2], sorted_array)
def test_two_elements_not_sorted(self):
array_to_sort = [2, 1]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1, 2], sorted_array)
def test_three_elements_not_sorted(self):
array_to_sort = [2, 1, 3]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1, 2, 3], sorted_array)
def test_three_elements_sorted(self):
array_to_sort = [1,2,3]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1, 2, 3], sorted_array)
def test_many_elements(self):
array_to_sort = [2, 1, 70, 8, 4, 45, 7, 7]
sorted_array = MergeSort.sort(array_to_sort)
self.assertEqual([1, 2, 4, 7, 7, 8, 45, 70], sorted_array)
I really like python and its unit testing framework. So simple to get going and for doing TDD.

No comments: