Created
March 5, 2025 19:53
-
-
Save holocronweaver/37e037d6b6cd1a9d12f5abf52b6805e2 to your computer and use it in GitHub Desktop.
Simple, Clear Python Merge Sort
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
#! /usr/bin/env python3 | |
import unittest | |
class MergeSort: | |
'''Partition list in half, then sort each half and merge the halves. | |
Merging does the actual sorting. It looks at the front of the left and right | |
halves and picks the smallest value to append to the merged list. | |
Time: O(n log n), memory: O(n) | |
''' | |
def sort(self, iterable): | |
if len(iterable) == 1: | |
return iterable | |
left, right = self._partition(iterable) | |
left = self.sort(left) | |
right = self.sort(right) | |
return self._merge(left, right) | |
def _partition(self, iterable): | |
split = len(iterable) // 2 | |
return iterable[:split], iterable[split:] | |
def _merge(self, left, right): | |
merged = [] | |
while left and right: | |
if left[0] < right[0]: | |
merged.append(left[0]) | |
del left[0] | |
else: | |
merged.append(right[0]) | |
del right[0] | |
if left: | |
merged.extend(left) | |
elif right: | |
merged.extend(right) | |
return merged | |
class SortTests(unittest.TestCase): | |
unsorted_list = [9, 6, 3, 3, 8, 1] | |
sorted_list = [1, 3, 3, 6, 8, 9] | |
def test_merge_sort(self): | |
sorter = MergeSort() | |
self._basic_test(sorter.sort) | |
def _basic_test(self, sort_method): | |
self.assertEqual( | |
sort_method(self.unsorted_list), | |
self.sorted_list | |
) | |
if __name__ == '__main__': | |
unittest.main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment