diff --git a/search.py b/search.py index c3f128c..41dbcd8 100644 --- a/search.py +++ b/search.py @@ -26,6 +26,10 @@ def linear(data: List[Any], target: Any, comparator: Callable[[Any, Any], bool]) Performs a linear search through the list. Returns the index of the target, or -1 if not found. """ + for i, item in enumerate(data): + if comparator(item, target): + return i + return -1 pass # ===================== @@ -42,5 +46,20 @@ def binary(data: List[Any], target: Any, comparator: Callable[[Any, Any], int]) - positive if a > b Returns the index of the found element, or -1 if not found. """ + left = 0 + right = len(data) - 1 + + while left <= right: + mid = (left + right) // 2 + comparison = comparator(data[mid], target) + + if comparison == 0: + return mid + elif comparison < 0: + left = mid + 1 + else: + right = mid - 1 + + return -1 pass diff --git a/sort.py b/sort.py index 402e60c..91f5b39 100644 --- a/sort.py +++ b/sort.py @@ -22,6 +22,16 @@ def merge(data: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any]: Returns: List[Any]: A new sorted list. """ + if len(data) <= 1: + return data.copy() + + # Spliting array + mid = len(data) // 2 + left = Sorter.merge(data[:mid], comparator) + right = Sorter.merge(data[mid:], comparator) + + # Merge + return Sorter._merge_halves(left, right, comparator) pass @staticmethod @@ -36,6 +46,18 @@ def insertion(data: List[Any], comparator: Callable[[Any, Any], bool]) -> List[A Returns: List[Any]: A new sorted list. """ + arr = data.copy() + + for i in range(1, len(arr)): + key = arr[i] + j = i - 1 + + while j >= 0 and not comparator(arr[j], key): + arr[j + 1] = arr[j] + j -= 1 + arr[j + 1] = key + + return arr pass @staticmethod @@ -50,6 +72,20 @@ def bubble(data: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any] Returns: List[Any]: A new sorted list. """ + arr = data.copy() + n = len(arr) + + for i in range(n): + swapped = False + for j in range(0, n - i - 1): + + if not comparator(arr[j], arr[j + 1]): + arr[j], arr[j + 1] = arr[j + 1], arr[j] + swapped = True + if not swapped: + break + + return arr pass @staticmethod @@ -68,5 +104,15 @@ def sort(data: List[Any], comparator: Callable[[Any, Any], bool], method: str = Raises: ValueError: If an unknown sort method is provided. """ + method = method.lower() + + if method == "merge": + return Sorter.merge(data, comparator) + if method == "insertion": + return Sorter.insertion(data, comparator) + if method == "bubble": + return Sorter.bubble(data, comparator) + + raise ValueError(f"Unknown sort method: {method}. Use 'merge', 'insertion', or 'bubble'.") pass