To accomplish this, we will start by defining the SortAlgorithm abstract class with two abstract methods, compare() and swap(), and a concrete sort() method which will provide the template for sorting.
Next, we'll implement specific sorting algorithm classes like BubbleSort and SelectionSort that inherit from SortAlgorithm and provide specific implementations of the sort() method, along with the compare() and swap() methods which will be required by any subclass.
1. Abstract class SortAlgorithm
from abc import ABC, abstractmethod
class SortAlgorithm(ABC):
def __init__(self, data):
self.data = data
@abstractmethod
def compare(self, a, b):
pass
@abstractmethod
def swap(self, i, j):
pass
def sort(self):
pass
2. Implement BubbleSort subclass
class BubbleSort(SortAlgorithm):
def compare(self, a, b):
return a > b
def swap(self, i, j):
self.data[i], self.data[j] = self.data[j], self.data[i]
def sort(self):
n = len(self.data)
for i in range(n):
for j in range(0, n-i-1):
if self.compare(self.data[j], self.data[j+1]):
self.swap(j, j+1)
3. Implement SelectionSort subclass
class SelectionSort(SortAlgorithm):
def compare(self, a, b):
return a > b
def swap(self, i, j):
self.data[i], self.data[j] = self.data[j], self.data[i]
def sort(self):
n = len(self.data)
for i in range(n):
min_idx = i
for j in range(i+1, n):
if self.compare(self.data[min_idx], self.data[j]):
min_idx = j
self.swap(min_idx, i)
4. Testing the implementation
def print_sorted(algorithm, data):
sorting_algorithm = algorithm(data)
sorting_algorithm.sort()
return sorting_algorithm.data
# Data to sort
data_int = [34, 7, 23, 32, 5, 62]
data_str = ["banana", "apple", "orange", "mango"]
# Sort using BubbleSort and SelectionSort
print("Sorted with BubbleSort:", print_sorted(BubbleSort, data_int.copy()))
print("Sorted with BubbleSort (Strings):", print_sorted(BubbleSort, data_str.copy()))
print("Sorted with SelectionSort:", print_sorted(SelectionSort, data_int.copy()))
print("Sorted with SelectionSort (Strings):", print_sorted(SelectionSort, data_str.copy()))
This Python code effectively demonstrates the Template Method design pattern for sorting algorithms. BubbleSort and SelectionSort implement the concrete behavior needed to perform sorting while conforming to the template defined in the SortAlgorithm abstract base class.