Created
January 3, 2021 21:50
-
-
Save srleyva/b74260dc33c219e8a35d92f66f4fef0f to your computer and use it in GitHub Desktop.
Messing around with sorting algos in python
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
from abc import ABC, abstractmethod | |
import unittest | |
from random import randint | |
import inspect | |
import sys | |
class Sort(ABC): | |
@abstractmethod | |
def sort(unsorted_list): | |
pass | |
@classmethod | |
def _swap(cls, unsorted_list, index_1, index_2): | |
unsorted_list[index_1], unsorted_list[index_2] = unsorted_list[index_2], unsorted_list[index_1] | |
class BubbleSort(Sort): | |
@classmethod | |
def sort(cls, unsorted_list): | |
for item in unsorted_list: | |
for i, item in enumerate(unsorted_list): | |
if i == 0: | |
continue | |
if unsorted_list[i-1] > item: | |
cls._swap(unsorted_list, i, i-1) | |
return unsorted_list | |
class QuickSort(Sort): | |
@classmethod | |
def sort(cls, unsorted_list): | |
if len(unsorted_list) < 2: | |
return unsorted_list | |
partition_point = cls._partition(unsorted_list) | |
low_side = cls.sort(unsorted_list[0:partition_point]) | |
high_side = cls.sort(unsorted_list[partition_point:]) | |
return low_side + high_side | |
@classmethod | |
def _partition(cls, unsorted_list): | |
pivot = len(unsorted_list)-1 | |
low_index = -1 | |
for i, item in enumerate(unsorted_list): | |
if item <= unsorted_list[pivot]: | |
low_index += 1 | |
cls._swap(unsorted_list, low_index, i) | |
if low_index != pivot: | |
cls._swap(unsorted_list, low_index+1, pivot) | |
return low_index | |
class TestSort(unittest.TestCase): | |
_rand_list = [ randint(0, 10) for _ in range(100) ] | |
_expected = sorted(_rand_list) | |
_classes_to_test = [ sort_class for sort_class in inspect.getmembers(sys.modules[__name__], inspect.isclass) if sort_class[0] not in ("Sort", "ABC") ] | |
def test_sort_methods(self): | |
for sort_class in self._classes_to_test: | |
print(f"Testing: {sort_class[0]}") | |
sorted_list = sort_class[1].sort(self._rand_list) | |
self.assertEqual(sorted_list, self._expected) | |
if __name__ == '__main__': | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment