Skip to content

Commit 0e05a29

Browse files
committed
Add sleep sort with doctest and type hints (Hacktoberfest 2025)
1 parent e2a78d4 commit 0e05a29

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

sorts/sleep_sort.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
# sorts/sleep_sort.py
2+
from __future__ import annotations
3+
4+
import threading
5+
import time
6+
from typing import List
7+
8+
9+
def sleep_sort(arr: List[int]) -> List[int]:
10+
"""
11+
"Sorts" a list by sleeping for each value's duration.
12+
Fun demo – **not** for production!
13+
14+
>>> import random; random.seed(42)
15+
>>> sleep_sort([3, 1, 4, 1, 5])
16+
[1, 1, 3, 4, 5]
17+
>>> sleep_sort([])
18+
[]
19+
>>> sleep_sort([42])
20+
[42]
21+
"""
22+
if not arr:
23+
return []
24+
25+
result: List[int] = []
26+
27+
def sleeper(value: int) -> None:
28+
time.sleep(value / 1000.0) # scale down for fast tests
29+
result.append(value)
30+
31+
threads = [threading.Thread(target=sleeper, args=(x,)) for x in arr]
32+
for t in threads:
33+
t.start()
34+
for t in threads:
35+
t.join()
36+
37+
return result
38+
39+
40+
if __name__ == "__main__":
41+
import doctest
42+
doctest.testmod(verbose=True)

0 commit comments

Comments
 (0)