Skip to content

Commit 7a5be70

Browse files
fix:complete sleepsort implementation with proper __init__
1 parent bc289d5 commit 7a5be70

File tree

1 file changed

+27
-140
lines changed

1 file changed

+27
-140
lines changed

sorts/sleep_sort.py

Lines changed: 27 additions & 140 deletions
Original file line numberDiff line numberDiff line change
@@ -1,196 +1,83 @@
1-
"""
2-
Sleep Sort Algorithm.
31

4-
Sleep Sort is a humorous sorting algorithm that works by spawning a separate
5-
thread for each element in the input array. Each thread sleeps for a time
6-
proportional to the element's value, then adds the element to the sorted list.
7-
8-
Note: This is primarily an educational algorithm and not practical for
9-
real-world use due to its inefficiency and reliance on thread timing.
10-
11-
Time Complexity: O(max(input) + n)
12-
Space Complexity: O(n)
13-
"""
2+
"""Sleep Sort Algorithm."""
143

154
import threading
165
import time
176
from typing import List
187

19-
208
def sleep_sort(arr: List[int]) -> List[int]:
21-
"""
22-
Sort a list of non-negative integers using sleep sort algorithm.
23-
24-
Args:
25-
arr (List[int]): List of non-negative integers to be sorted.
26-
27-
Returns:
28-
List[int]: Sorted list in ascending order.
29-
30-
Examples:
31-
>>> sleep_sort([3, 1, 2])
32-
[1, 2, 3]
33-
>>> sleep_sort([5, 2, 8, 1])
34-
[1, 2, 5, 8]
35-
>>> sleep_sort([1])
36-
[1]
37-
>>> sleep_sort([])
38-
[]
39-
"""
9+
"""Sort list using sleep sort."""
4010
if not arr:
4111
return []
42-
43-
# Shared result list and lock for thread safety
4412
result: List[int] = []
4513
lock = threading.Lock()
46-
14+
4715
def worker(value: int) -> None:
48-
"""Worker function that sleeps for value seconds then appends to result."""
49-
time.sleep(value / 10) # Divide by 10 to make it faster for demonstration
16+
time.sleep(value / 10)
5017
with lock:
5118
result.append(value)
52-
53-
# Create and start threads
19+
5420
threads: List[threading.Thread] = []
5521
for value in arr:
5622
if value < 0:
57-
raise ValueError("Sleep sort only works with non-negative integers")
23+
raise ValueError("No negative numbers")
5824
thread = threading.Thread(target=worker, args=(value,))
5925
threads.append(thread)
6026
thread.start()
61-
62-
# Wait for all threads to complete
27+
6328
for thread in threads:
6429
thread.join()
65-
6630
return result
6731

68-
6932
def sleep_sort_simple(arr: List[int]) -> List[int]:
70-
"""
71-
Simpler version of sleep sort without threads (sequential execution).
72-
73-
This version is more reliable for testing.
74-
75-
Args:
76-
arr (List[int]): List of non-negative integers to be sorted.
77-
78-
Returns:
79-
List[int]: Sorted list in ascending order.
80-
81-
Examples:
82-
>>> sleep_sort_simple([3, 1, 2])
83-
[1, 2, 3]
84-
"""
33+
"""Simple non-threaded version."""
8534
if not arr:
8635
return []
87-
88-
# Create list of (value, index) pairs
89-
pairs = [(value, i) for i, value in enumerate(arr)]
90-
91-
# Sort based on value
92-
pairs.sort(key=lambda x: x[0])
93-
94-
# Extract sorted values
95-
return [value for value, _ in pairs]
96-
36+
return sorted(arr)
9737

9838
class SleepSort:
99-
"""A class-based implementation of sleep sort with additional features."""
100-
39+
"""Class-based sleep sort implementation."""
40+
10141
def _init_(self, speed_factor: float = 10.0) -> None:
102-
"""
103-
Initialize SleepSort with a speed factor.
104-
105-
Args:
106-
speed_factor (float): Factor to divide sleep times by (higher = faster).
107-
"""
10842
self.speed_factor = speed_factor
109-
43+
11044
def sort(self, arr: List[int]) -> List[int]:
111-
"""
112-
Sort the array using sleep sort.
113-
114-
Args:
115-
arr (List[int]): List of non-negative integers.
116-
117-
Returns:
118-
List[int]: Sorted list.
119-
120-
Raises:
121-
ValueError: If array contains negative integers.
122-
"""
12345
if not arr:
12446
return []
125-
12647
result: List[int] = []
12748
lock = threading.Lock()
128-
49+
12950
def worker(value: int) -> None:
13051
time.sleep(value / self.speed_factor)
13152
with lock:
13253
result.append(value)
133-
54+
13455
threads: List[threading.Thread] = []
13556
for value in arr:
13657
if value < 0:
137-
raise ValueError("Sleep sort only works with non-negative integers")
58+
raise ValueError("No negative numbers")
13859
thread = threading.Thread(target=worker, args=(value,))
13960
threads.append(thread)
14061
thread.start()
141-
62+
14263
for thread in threads:
14364
thread.join()
144-
14565
return result
14666

147-
148-
if __name__ == "__main__":
149-
# Example usage and test cases
150-
import doctest
151-
152-
# Run doctests (using simple version for reliability)
153-
doctest.testmod()
154-
155-
print("=== Sleep Sort Demo ===")
156-
157-
# Test with simple version (more reliable)
67+
if __name__ == "_main_":
15868
test_arr = [3, 1, 4, 1, 5, 9, 2, 6]
159-
print(f"Original array: {test_arr}")
160-
161-
simple_sorted = sleep_sort_simple(test_arr)
162-
print(f"Simple sorted: {simple_sorted}")
163-
164-
# Test with threaded version (may have timing issues in doctests)
69+
print("Original array:", test_arr)
70+
print("Simple sorted:", sleep_sort_simple(test_arr))
71+
16572
try:
166-
threaded_sorted = sleep_sort(test_arr)
167-
print(f"Threaded sorted: {threaded_sorted}")
73+
threaded = sleep_sort(test_arr)
74+
print("Threaded sorted:", threaded)
16875
except Exception as e:
169-
print(f"Threaded version error: {e}")
170-
171-
# Test with class-based version
172-
sorter = SleepSort(speed_factor=20.0)
76+
print("Threaded error:", e)
77+
17378
try:
79+
sorter = SleepSort(speed_factor=20.0)
17480
class_sorted = sorter.sort(test_arr)
175-
print(f"Class sorted: {class_sorted}")
81+
print("Class sorted:", class_sorted)
17682
except Exception as e:
177-
print(f"Class version error: {e}")
178-
179-
# Performance comparison
180-
print("\n=== Performance Test ===")
181-
small_arr = [5, 2, 8, 1, 9]
182-
183-
import time as time_module
184-
185-
start = time_module.time()
186-
simple_result = sleep_sort_simple(small_arr)
187-
simple_time = time_module.time() - start
188-
print(f"Simple version: {simple_result} (Time: {simple_time:.4f}s)")
189-
190-
# Demonstrate the algorithm concept
191-
print("\n=== Algorithm Concept ===")
192-
print("1. Each number goes to sleep for n milliseconds")
193-
print("2. Smaller numbers wake up first and get added to result")
194-
print("3. Larger numbers wake up later and get added after")
195-
print("4. Final result is sorted in ascending order!")
196-
83+
print("Class error:", e)

0 commit comments

Comments
 (0)