Define a class SortingAlgorithm
with a method sort()
. Implement child classes QuickSort
, MergeSort
, and BubbleSort
that override the sort()
method to sort an array using their respective algorithms.
Example 1:
Input: QuickSort with array [3, 1, 4, 1, 5, 9, 2, 6] Output: [1, 1, 2, 3, 4, 5, 6, 9]
Example 2:
Input: BubbleSort with array [3, 1, 4, 1, 5, 9, 2, 6] Output: [1, 1, 2, 3, 4, 5, 6, 9]
Implement the sort()
method in each subclass to return the sorted array. Note: actual implementations of quick sort and merge sort are outside the scope of this question, you can use built-in sort for the purpose of this example.
class SortingAlgorithm: def sort(self, arr): pass class QuickSort(SortingAlgorithm): def sort(self, arr): return sorted(arr) class MergeSort(SortingAlgorithm): def sort(self, arr): return sorted(arr) class BubbleSort(SortingAlgorithm): def sort(self, arr): return sorted(arr) # Test the classes quick_sort = QuickSort() print(quick_sort.sort([3, 1, 4, 1, 5, 9, 2, 6])) # Output: [1, 1, 2, 3, 4, 5, 6, 9] bubble_sort = BubbleSort() print(bubble_sort.sort([3, 1, 4, 1, 5, 9, 2, 6])) # Output: [1, 1, 2, 3, 4, 5, 6, 9]
Unlock AI & Data Science treasures. Log in!