Skip to content

Commit f153d29

Browse files
feat: complete sleep sort implementation with tests and error handling
2 parents 6d49334 + 3fb4f0f commit f153d29

File tree

1 file changed

+78
-20
lines changed

1 file changed

+78
-20
lines changed

sorts/sleep_sort.py

Lines changed: 78 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,95 @@
1+
"""
2+
Sleep Sort Algorithm Implementation
3+
4+
Sleep sort works by creating a separate thread for each element in the input array,
5+
where each thread sleeps for a duration proportional to the element's value.
6+
When the thread wakes up, the element is appended to the result list.
7+
Smaller values wake up first, resulting in a sorted list.
8+
"""
9+
110
import threading
211
import time
312

13+
414
def sleep_sort(arr: list[int]) -> list[int]:
515
"""
6-
Sleep sort implementation - each element sleeps for n seconds then gets appended
16+
Sort list using sleep sort algorithm.
17+
18+
Args:
19+
arr: List of non-negative integers
20+
21+
Returns:
22+
Sorted list in ascending order
23+
24+
Examples:
25+
>>> sleep_sort([3, 1, 4, 2])
26+
[1, 2, 3, 4]
27+
>>> sleep_sort([])
28+
[]
29+
>>> sleep_sort([5])
30+
[5]
731
"""
832
if not arr:
933
return []
10-
11-
result = []
12-
13-
def add_to_result(n):
14-
time.sleep(n)
15-
result.append(n)
16-
34+
35+
result: list[int] = []
36+
lock = threading.Lock()
37+
38+
def add_to_result(value: int) -> None:
39+
time.sleep(value)
40+
with lock:
41+
result.append(value)
42+
1743
threads = []
1844
for num in arr:
45+
if num < 0:
46+
raise ValueError("Sleep sort only works with non-negative integers")
1947
thread = threading.Thread(target=add_to_result, args=(num,))
2048
thread.start()
2149
threads.append(thread)
22-
50+
2351
for thread in threads:
2452
thread.join()
25-
53+
2654
return result
2755

28-
if __name__ == "__main__":
29-
# Test the sleep sort
30-
user_input = input("Enter numbers separated by commas: ")
31-
if user_input:
32-
numbers = [int(x) for x in user_input.split(",")]
33-
print("Original:", numbers)
34-
sorted_numbers = sleep_sort(numbers)
35-
print("Sorted:", sorted_numbers)
36-
else:
37-
print("No input provided")
56+
57+
def test_sleep_sort() -> None:
58+
"""Test sleep sort algorithm with various test cases."""
59+
# Test basic functionality
60+
assert sleep_sort([3, 1, 4, 2]) == [1, 2, 3, 4]
61+
62+
# Test edge cases
63+
assert sleep_sort([]) == []
64+
assert sleep_sort([5]) == [5]
65+
assert sleep_sort([1, 1, 1]) == [1, 1, 1]
66+
assert sleep_sort([1, 2, 3, 4, 5]) == [1, 2, 3, 4, 5]
67+
assert sleep_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
68+
69+
print("All tests passed!")
70+
71+
72+
if __name__ == "_main_":
73+
# Run automated tests
74+
test_sleep_sort()
75+
76+
# Interactive demo
77+
try:
78+
user_input = input("Enter non-negative numbers separated by commas: ").strip()
79+
if user_input:
80+
numbers = [int(x.strip()) for x in user_input.split(",")]
81+
print(f"Original list: {numbers}")
82+
83+
# Validate input
84+
if any(num < 0 for num in numbers):
85+
print("Error: Sleep sort only works with non-negative integers")
86+
else:
87+
print("Sorting... (this will take time proportional to the largest number)")
88+
sorted_numbers = sleep_sort(numbers)
89+
print(f"Sorted list: {sorted_numbers}")
90+
else:
91+
print("No input provided.")
92+
except ValueError:
93+
print("Error: Please enter valid integers separated by commas.")
94+
except KeyboardInterrupt:
95+
print("\nProgram interrupted by user.")

0 commit comments

Comments
 (0)