Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions search.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

# =====================
Expand All @@ -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

46 changes: 46 additions & 0 deletions sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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