Skip to content
Closed
Changes from 2 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
100 changes: 100 additions & 0 deletions sorts/sleep_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Sleep sort (novelty) implementation
# This provides a fast simulated mode (default) plus an optional real threaded mode.

from typing import List

Check failure on line 4 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP035)

sorts/sleep_sort.py:4:1: UP035 `typing.List` is deprecated, use `list` instead
import threading
import time

Check failure on line 6 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (I001)

sorts/sleep_sort.py:4:1: I001 Import block is un-sorted or un-formatted


def sleep_sort(a: List[int], simulate: bool = True, scale: float = 0.01) -> None:

Check failure on line 9 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:9:19: UP006 Use `list` instead of `List` for type annotation
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Please provide descriptive name for the parameter: a

"""
Sort the list a in-place using the sleep sort idea.

Behavior:
- Destructive: modifies list a.
- Only accepts integers (positive, zero, or negative).
- Default simulate=True runs instantly by simulating timed wake-ups (safe for tests/CI).

Check failure on line 16 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/sleep_sort.py:16:89: E501 Line too long (92 > 88)
- If simulate=False the function spawns one thread per element and uses time.sleep;
use that mode only for small inputs (and beware of real waiting).
- scale (seconds per unit) applies only when simulate=False.

>>> a = [3, 1, 2]
>>> b = sorted(a)
>>> sleep_sort(a) # simulated, fast
>>> a == b
True

>>> a = [0, 0, 1]
>>> sleep_sort(a)
>>> a
[0, 0, 1]

>>> a = [-2, 1, 0]
>>> sleep_sort(a)
>>> a == sorted([-2, 1, 0])
True

>>> sleep_sort([1.5, 2]) # non-integers not allowed
Traceback (most recent call last)
...
TypeError: integers only please
"""
# quick no-op for empty
if not a:
return

# type checks
if any(not isinstance(x, int) for x in a):
raise TypeError("integers only please")

# handle negatives by offsetting so all "sleep times" are non-negative
min_val = min(a)
offset = -min_val if min_val < 0 else 0

if simulate:
# Simulated wake-up: bucket by wake time (value + offset), preserve original order

Check failure on line 55 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (E501)

sorts/sleep_sort.py:55:89: E501 Line too long (90 > 88)
buckets = {}
for idx, val in enumerate(a):
wake = val + offset
buckets.setdefault(wake, []).append((idx, val))
result: List[int] = []

Check failure on line 60 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:60:17: UP006 Use `list` instead of `List` for type annotation
for wake in sorted(buckets.keys()):
# append in original order to make stable when values equal
for _, val in buckets[wake]:
result.append(val)
a[:] = result
return

# Real threaded mode (be careful: this actually sleeps)
results: List[int] = []

Check failure on line 69 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:69:14: UP006 Use `list` instead of `List` for type annotation
lock = threading.Lock()

def worker(value: int) -> None:
Copy link
Copy Markdown

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

Copy link
Copy Markdown

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

# sleep proportional to value (after offset), then append to results
time.sleep((value + offset) * scale)
with lock:
results.append(value)

threads: List[threading.Thread] = []

Check failure on line 78 in sorts/sleep_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (UP006)

sorts/sleep_sort.py:78:14: UP006 Use `list` instead of `List` for type annotation
for val in a:
t = threading.Thread(target=worker, args=(val,))
t.daemon = True
t.start()
threads.append(t)

# wait for threads to finish
for t in threads:
t.join()

# results is in the order threads woke up
a[:] = results


def main() -> None:
Copy link
Copy Markdown

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 main

a = [8, 3, 2, 7, 4, 6, 8]
sleep_sort(a) # simulated (fast)
print("Sorted order is:", " ".join(map(str, a)))


if __name__ == "__main__":
main()
Loading