Skip to content
Open
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
35 changes: 34 additions & 1 deletion sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,40 @@ def bubble(data: List[Any], comparator: Callable[[Any, Any], bool]) -> List[Any]
Returns:
List[Any]: A new sorted list.
"""
pass
# Handle empty or single-element lists
if len(data) <= 1:
return data[:]

# Create a copy to avoid modifying the original list
result = data[:]
n = len(result)

# Flag to optimize for already sorted lists
swapped = True

# Keep track of last swap position to optimize range
last_swap = n - 1

while swapped:
swapped = False
next_last_swap = 0

# Only iterate up to the last swap position from previous pass
for i in range(last_swap):
# If the elements are in wrong order, swap them
if not comparator(result[i], result[i + 1]):
result[i], result[i + 1] = result[i + 1], result[i]
swapped = True
next_last_swap = i

# Update last swap position for next pass
last_swap = next_last_swap

# If no swaps occurred, list is sorted
if not swapped:
break

return result

@staticmethod
def sort(data: List[Any], comparator: Callable[[Any, Any], bool], method: str = "merge") -> List[Any]:
Expand Down