Skip to content

Commit 97a8891

Browse files
Sai Rahul GuggilamSai Rahul Guggilam
authored andcommitted
Sleep sort
1 parent 21e9b86 commit 97a8891

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

sorts/sleep_sort.py

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
"""
2+
An implementation of Sleep Sort.
3+
4+
Description
5+
-----------
6+
Sleep Sort is a highly unconventional algorithm that leverages timing delays
7+
to produce a sorted sequence. Each element in the array is assigned to a thread
8+
that sleeps for a duration proportional to its value. As threads "wake up,"
9+
they output numbers in increasing order.
10+
11+
This algorithm only works for non-negative integers and is non-deterministic
12+
in real systems due to thread scheduling and timing inaccuracies.
13+
14+
Time complexity: O(n) expected (but unreliable in practice)
15+
Space complexity: O(n) for thread management
16+
"""
17+
18+
import threading
19+
import time
20+
from typing import List
21+
22+
23+
def sleep_sort(arr: List[int]) -> List[int]:
24+
"""
25+
Sorts a list of non-negative integers using the Sleep Sort algorithm.
26+
27+
Parameters
28+
----------
29+
arr : List[int]
30+
A list of non-negative integers to be sorted.
31+
32+
Returns
33+
-------
34+
List[int]
35+
A new list containing the elements in sorted order.
36+
37+
Example
38+
-------
39+
>>> sleep_sort([3, 1, 2])
40+
[1, 2, 3]
41+
"""
42+
if not arr:
43+
return []
44+
45+
result: List[int] = []
46+
threads = []
47+
48+
def _sleep_and_append(n: int) -> None:
49+
"""Sleeps for n * 0.01 seconds and appends n to the result."""
50+
time.sleep(n * 0.01)
51+
result.append(n)
52+
53+
for num in arr:
54+
if num < 0:
55+
raise ValueError("Sleep Sort only supports non-negative integers.")
56+
thread = threading.Thread(target=_sleep_and_append, args=(num,))
57+
threads.append(thread)
58+
thread.start()
59+
60+
for thread in threads:
61+
thread.join()
62+
63+
return result
64+
65+
66+
def _test() -> None:
67+
"""Basic test cases for sleep_sort."""
68+
test_cases = [
69+
[],
70+
[1],
71+
[3, 1, 2],
72+
[0, 0, 1],
73+
[5, 3, 9, 1, 4],
74+
]
75+
76+
for case in test_cases:
77+
sorted_case = sorted(case)
78+
assert sleep_sort(case) == sorted_case, f"Failed on {case}"
79+
print("All tests passed.")
80+
81+
82+
if __name__ == "__main__":
83+
_test()

0 commit comments

Comments
 (0)