This file contains 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
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 |
And hear's the unit tests (of course the unit tests came first!):
This file contains 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
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) |
No comments:
Post a Comment