Skip to content

Commit 43b52fb

Browse files
committed
### Summary
Add sorts/sleep_sort.py: a novelty sleep-sort implementation with a simulated mode (safe for CI) and an optional real threaded mode. ### Files added - sorts/sleep_sort.py ### Notes - File name is snake_case. - Includes doctests; tested with python -m doctest -v sort/sleep_sort.py. - Follows repository style. If this addresses an issue, add: Fixes #<issue-number>
1 parent 35e74cb commit 43b52fb

File tree

1 file changed

+31
-48
lines changed

1 file changed

+31
-48
lines changed

sorts/sleep_sort.py

Lines changed: 31 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -1,100 +1,83 @@
1-
# Sleep sort (novelty) implementation
2-
# This provides a fast simulated mode (default) plus an optional real threaded mode.
3-
41
from typing import List
52
import threading
63
import time
74

85

9-
def sleep_sort(a: List[int], simulate: bool = True, scale: float = 0.01) -> None:
6+
def sleep_sort(numbers: List[int], simulate: bool = True, scale: float = 0.01) -> None:
107
"""
11-
Sort the list a in-place using the sleep sort idea.
8+
Perform Sleep Sort on the given list of integers.
9+
10+
Sorts the list numbers in place using the Sleep Sort algorithm.
1211
1312
Behavior:
14-
- Destructive: modifies list a.
13+
- Destructive: modifies the list numbers.
1514
- Only accepts integers (positive, zero, or negative).
1615
- Default simulate=True runs instantly by simulating timed wake-ups (safe for tests/CI).
17-
- If simulate=False the function spawns one thread per element and uses time.sleep;
18-
use that mode only for small inputs (and beware of real waiting).
16+
- If simulate=False, the function spawns one thread per element and uses time.sleep;
17+
this mode causes real waiting time proportional to element values.
1918
- scale (seconds per unit) applies only when simulate=False.
2019
21-
>>> a = [3, 1, 2]
22-
>>> b = sorted(a)
23-
>>> sleep_sort(a) # simulated, fast
24-
>>> a == b
25-
True
20+
Examples
21+
--------
22+
>>> nums = [3, 1, 2]
23+
>>> sleep_sort(nums)
24+
>>> nums
25+
[1, 2, 3]
2626
27-
>>> a = [0, 0, 1]
28-
>>> sleep_sort(a)
29-
>>> a
27+
>>> nums = [0, 0, 1]
28+
>>> sleep_sort(nums)
29+
>>> nums
3030
[0, 0, 1]
3131
32-
>>> a = [-2, 1, 0]
33-
>>> sleep_sort(a)
34-
>>> a == sorted([-2, 1, 0])
35-
True
32+
>>> nums = [-2, 1, 0]
33+
>>> sleep_sort(nums)
34+
>>> nums
35+
[-2, 0, 1]
3636
37-
>>> sleep_sort([1.5, 2]) # non-integers not allowed
38-
Traceback (most recent call last)
37+
>>> sleep_sort([1.5, 2])
38+
Traceback (most recent call last):
3939
...
4040
TypeError: integers only please
4141
"""
42-
# quick no-op for empty
43-
if not a:
42+
if not numbers:
4443
return
4544

46-
# type checks
47-
if any(not isinstance(x, int) for x in a):
45+
if any(not isinstance(x, int) for x in numbers):
4846
raise TypeError("integers only please")
4947

50-
# handle negatives by offsetting so all "sleep times" are non-negative
51-
min_val = min(a)
48+
min_val = min(numbers)
5249
offset = -min_val if min_val < 0 else 0
5350

5451
if simulate:
55-
# Simulated wake-up: bucket by wake time (value + offset), preserve original order
52+
# Simulated wake-up: bucket by wake time (value + offset), preserve order
5653
buckets = {}
57-
for idx, val in enumerate(a):
54+
for idx, val in enumerate(numbers):
5855
wake = val + offset
5956
buckets.setdefault(wake, []).append((idx, val))
6057
result: List[int] = []
6158
for wake in sorted(buckets.keys()):
62-
# append in original order to make stable when values equal
6359
for _, val in buckets[wake]:
6460
result.append(val)
65-
a[:] = result
61+
numbers[:] = result
6662
return
6763

68-
# Real threaded mode (be careful: this actually sleeps)
64+
# Real threaded mode: causes actual delays proportional to element values
6965
results: List[int] = []
7066
lock = threading.Lock()
7167

7268
def worker(value: int) -> None:
73-
# sleep proportional to value (after offset), then append to results
7469
time.sleep((value + offset) * scale)
7570
with lock:
7671
results.append(value)
7772

7873
threads: List[threading.Thread] = []
79-
for val in a:
74+
for val in numbers:
8075
t = threading.Thread(target=worker, args=(val,))
8176
t.daemon = True
8277
t.start()
8378
threads.append(t)
8479

85-
# wait for threads to finish
8680
for t in threads:
8781
t.join()
8882

89-
# results is in the order threads woke up
90-
a[:] = results
91-
92-
93-
def main() -> None:
94-
a = [8, 3, 2, 7, 4, 6, 8]
95-
sleep_sort(a) # simulated (fast)
96-
print("Sorted order is:", " ".join(map(str, a)))
97-
98-
99-
if __name__ == "__main__":
100-
main()
83+
numbers[:] = results

0 commit comments

Comments
 (0)