Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
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
132 changes: 0 additions & 132 deletions sorts/bubble_sort.py
Original file line number Diff line number Diff line change
@@ -1,132 +0,0 @@
from typing import Any


def bubble_sort_iterative(collection: list[Any]) -> list[Any]:
"""Pure implementation of bubble sort algorithm in Python

:param collection: some mutable ordered collection with heterogeneous
comparable items inside
:return: the same collection ordered by ascending

Examples:
>>> bubble_sort_iterative([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort_iterative([])
[]
>>> bubble_sort_iterative([-2, -45, -5])
[-45, -5, -2]
>>> bubble_sort_iterative([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> bubble_sort_iterative([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> bubble_sort_iterative([]) == sorted([])
True
>>> bubble_sort_iterative([-2, -45, -5]) == sorted([-2, -45, -5])
True
>>> bubble_sort_iterative([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
>>> bubble_sort_iterative(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
True
>>> bubble_sort_iterative(['z', 'a', 'y', 'b', 'x', 'c'])
['a', 'b', 'c', 'x', 'y', 'z']
>>> bubble_sort_iterative([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
>>> bubble_sort_iterative([1, 3.3, 5, 7.7, 2, 4.4, 6])
[1, 2, 3.3, 4.4, 5, 6, 7.7]
>>> import random
>>> collection_arg = random.sample(range(-50, 50), 100)
>>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
True
>>> import string
>>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
>>> bubble_sort_iterative(collection_arg) == sorted(collection_arg)
True
"""
length = len(collection)
for i in reversed(range(length)):
swapped = False
for j in range(i):
if collection[j] > collection[j + 1]:
swapped = True
collection[j], collection[j + 1] = collection[j + 1], collection[j]
if not swapped:
break # Stop iteration if the collection is sorted.
return collection


def bubble_sort_recursive(collection: list[Any]) -> list[Any]:
"""It is similar iterative bubble sort but recursive.

:param collection: mutable ordered sequence of elements
:return: the same list in ascending order

Examples:
>>> bubble_sort_recursive([0, 5, 2, 3, 2])
[0, 2, 2, 3, 5]
>>> bubble_sort_iterative([])
[]
>>> bubble_sort_recursive([-2, -45, -5])
[-45, -5, -2]
>>> bubble_sort_recursive([-23, 0, 6, -4, 34])
[-23, -4, 0, 6, 34]
>>> bubble_sort_recursive([0, 5, 2, 3, 2]) == sorted([0, 5, 2, 3, 2])
True
>>> bubble_sort_recursive([]) == sorted([])
True
>>> bubble_sort_recursive([-2, -45, -5]) == sorted([-2, -45, -5])
True
>>> bubble_sort_recursive([-23, 0, 6, -4, 34]) == sorted([-23, 0, 6, -4, 34])
True
>>> bubble_sort_recursive(['d', 'a', 'b', 'e']) == sorted(['d', 'a', 'b', 'e'])
True
>>> bubble_sort_recursive(['z', 'a', 'y', 'b', 'x', 'c'])
['a', 'b', 'c', 'x', 'y', 'z']
>>> bubble_sort_recursive([1.1, 3.3, 5.5, 7.7, 2.2, 4.4, 6.6])
[1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7]
>>> bubble_sort_recursive([1, 3.3, 5, 7.7, 2, 4.4, 6])
[1, 2, 3.3, 4.4, 5, 6, 7.7]
>>> bubble_sort_recursive(['a', 'Z', 'B', 'C', 'A', 'c'])
['A', 'B', 'C', 'Z', 'a', 'c']
>>> import random
>>> collection_arg = random.sample(range(-50, 50), 100)
>>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
True
>>> import string
>>> collection_arg = random.choices(string.ascii_letters + string.digits, k=100)
>>> bubble_sort_recursive(collection_arg) == sorted(collection_arg)
True
"""
length = len(collection)
swapped = False
for i in range(length - 1):
if collection[i] > collection[i + 1]:
collection[i], collection[i + 1] = collection[i + 1], collection[i]
swapped = True

return collection if not swapped else bubble_sort_recursive(collection)


if __name__ == "__main__":
import doctest
from random import sample
from timeit import timeit

doctest.testmod()

# Benchmark: Iterative seems slightly faster than recursive.
num_runs = 10_000
unsorted = sample(range(-50, 50), 100)
timer_iterative = timeit(
"bubble_sort_iterative(unsorted[:])", globals=globals(), number=num_runs
)
print("\nIterative bubble sort:")
print(*bubble_sort_iterative(unsorted), sep=",")
print(f"Processing time (iterative): {timer_iterative:.5f}s for {num_runs:,} runs")

unsorted = sample(range(-50, 50), 100)
timer_recursive = timeit(
"bubble_sort_recursive(unsorted[:])", globals=globals(), number=num_runs
)
print("\nRecursive bubble sort:")
print(*bubble_sort_recursive(unsorted), sep=",")
print(f"Processing time (recursive): {timer_recursive:.5f}s for {num_runs:,} runs")
108 changes: 108 additions & 0 deletions sorts/sleep_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
"""
Sleep Sort Algorithm Implementation
"""

import threading
import time
from typing import List

Check failure on line 7 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

sorts/sleep_sort.py:7:1: UP035 `typing.List` is deprecated, use `list` instead


def sleep_sort(arr: List[int]) -> List[int]:

Check failure on line 10 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:10:35: UP006 Use `list` instead of `List` for type annotation

Check failure on line 10 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:10:21: UP006 Use `list` instead of `List` for type annotation

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/sleep_sort.py, please provide doctest for the function sleep_sort

"""
Sort list using sleep sort algorithm.

Check failure on line 13 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:13:1: W293 Blank line contains whitespace
Args:
arr: List of non-negative integers

Check failure on line 16 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:16:1: W293 Blank line contains whitespace
Returns:
Sorted list in ascending order
"""
if not arr:
return []

Check failure on line 22 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:22:1: W293 Blank line contains whitespace
result = []
lock = threading.Lock()

Check failure on line 25 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:25:1: W293 Blank line contains whitespace
def worker(value):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/sleep_sort.py, please provide doctest for the function worker

Please provide return type hint for the function: worker. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: value

time.sleep(value / 10)
with lock:
result.append(value)

Check failure on line 30 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:30:1: W293 Blank line contains whitespace
threads = []
for value in arr:
if value < 0:
raise ValueError("No negative numbers allowed")
thread = threading.Thread(target=worker, args=(value,))
threads.append(thread)
thread.start()

Check failure on line 38 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:38:1: W293 Blank line contains whitespace
for thread in threads:
thread.join()

Check failure on line 41 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (W293)

sorts/sleep_sort.py:41:1: W293 Blank line contains whitespace
return result


class SleepSort:
"""Class-based sleep sort implementation."""

def _init_(self, speed_factor=10.0):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/sleep_sort.py, please provide doctest for the function _init_

Please provide return type hint for the function: _init_. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: speed_factor

self.speed_factor = speed_factor

def sort(self, arr):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/sleep_sort.py, please provide doctest for the function sort

Please provide return type hint for the function: sort. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: arr

"""
Sort array using sleep sort.

Args:
arr: List of non-negative integers

Returns:
Sorted list
"""
if not arr:
return []

result = []
lock = threading.Lock()

def worker(value):

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As there is no test file in this pull request nor any test function or class in the file sorts/sleep_sort.py, please provide doctest for the function worker

Please provide return type hint for the function: worker. If the function does not return a value, please provide the type hint as: def function() -> None:

Please provide type hint for the parameter: value

time.sleep(value / self.speed_factor)
with lock:
result.append(value)

threads = []
for value in arr:
if value < 0:
raise ValueError("No negative numbers allowed")
thread = threading.Thread(target=worker, args=(value,))
threads.append(thread)
thread.start()

for thread in threads:
thread.join()

return result


if __name__ == "_main_":
# Test the algorithms
test_data = [3, 1, 4, 1, 5, 9, 2, 6]

print("Original array:", test_data)

# Test basic sleep sort
try:
sorted1 = sleep_sort(test_data)
print("Basic sleep sort:", sorted1)
except Exception as e:
print("Basic sleep sort error:", e)

# Test class-based sleep sort
try:
sorter = SleepSort(speed_factor=20.0)
sorted2 = sorter.sort(test_data)
print("Class sleep sort:", sorted2)
except Exception as e:
print("Class sleep sort error:", e)

print("Algorithm completed successfully!")