11"""
2- Sleep Sort Algorithm
2+ Sleep Sort Algorithm.
33
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
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
66proportional to the element's value, then adds the element to the sorted list.
77
8- Note: This is primarily an educational algorithm and not practical for
8+ Note: This is primarily an educational algorithm and not practical for
99real-world use due to its inefficiency and reliance on thread timing.
1010
1111Time Complexity: O(max(input) + n)
1919
2020def sleep_sort (arr : List [int ]) -> List [int ]:
2121 """
22- Sorts a list of non-negative integers using sleep sort algorithm.
23-
22+ Sort a list of non-negative integers using sleep sort algorithm.
23+
2424 Args:
25- arr (List[int]): List of non-negative integers to be sorted
26-
25+ arr (List[int]): List of non-negative integers to be sorted.
26+
2727 Returns:
28- List[int]: Sorted list in ascending order
29-
28+ List[int]: Sorted list in ascending order.
29+
3030 Examples:
31- >>> sleep_sort([3, 1, 2])
32- [1, 2, 3]
33-
34- >>> sleep_sort([5, 2, 8, 1])
35- [1, 2, 5, 8]
36-
37- >>> sleep_sort([1])
38- [1]
39-
40- >>> sleep_sort([])
41- []
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+ []
4239 """
4340 if not arr :
4441 return []
45-
42+
4643 # Shared result list and lock for thread safety
47- result = []
44+ result : List [ int ] = []
4845 lock = threading .Lock ()
49-
46+
5047 def worker (value : int ) -> None :
5148 """Worker function that sleeps for value seconds then appends to result."""
5249 time .sleep (value / 10 ) # Divide by 10 to make it faster for demonstration
5350 with lock :
5451 result .append (value )
55-
52+
5653 # Create and start threads
57- threads = []
54+ threads : List [ threading . Thread ] = []
5855 for value in arr :
5956 if value < 0 :
6057 raise ValueError ("Sleep sort only works with non-negative integers" )
6158 thread = threading .Thread (target = worker , args = (value ,))
6259 threads .append (thread )
6360 thread .start ()
64-
61+
6562 # Wait for all threads to complete
6663 for thread in threads :
6764 thread .join ()
68-
65+
6966 return result
7067
7168
7269def sleep_sort_simple (arr : List [int ]) -> List [int ]:
7370 """
74- A simpler version of sleep sort without threads (sequential execution).
71+ Simpler version of sleep sort without threads (sequential execution).
72+
7573 This version is more reliable for testing.
76-
74+
7775 Args:
78- arr (List[int]): List of non-negative integers to be sorted
79-
76+ arr (List[int]): List of non-negative integers to be sorted.
77+
8078 Returns:
81- List[int]: Sorted list in ascending order
79+ List[int]: Sorted list in ascending order.
80+
81+ Examples:
82+ >>> sleep_sort_simple([3, 1, 2])
83+ [1, 2, 3]
8284 """
8385 if not arr :
8486 return []
85-
87+
8688 # Create list of (value, index) pairs
8789 pairs = [(value , i ) for i , value in enumerate (arr )]
88-
90+
8991 # Sort based on value
9092 pairs .sort (key = lambda x : x [0 ])
91-
93+
9294 # Extract sorted values
9395 return [value for value , _ in pairs ]
9496
9597
9698class SleepSort :
97- """
98- A class-based implementation of sleep sort with additional features.
99- """
100-
101- def _init_ (self , speed_factor : float = 10.0 ):
99+ """A class-based implementation of sleep sort with additional features."""
100+
101+ def _init_ (self , speed_factor : float = 10.0 ) -> None :
102102 """
103103 Initialize SleepSort with a speed factor.
104-
104+
105105 Args:
106- speed_factor (float): Factor to divide sleep times by (higher = faster)
106+ speed_factor (float): Factor to divide sleep times by (higher = faster).
107107 """
108108 self .speed_factor = speed_factor
109-
109+
110110 def sort (self , arr : List [int ]) -> List [int ]:
111111 """
112112 Sort the array using sleep sort.
113-
113+
114114 Args:
115- arr (List[int]): List of non-negative integers
116-
115+ arr (List[int]): List of non-negative integers.
116+
117117 Returns:
118- List[int]: Sorted list
118+ List[int]: Sorted list.
119+
120+ Raises:
121+ ValueError: If array contains negative integers.
119122 """
120123 if not arr :
121124 return []
122-
123- result = []
125+
126+ result : List [ int ] = []
124127 lock = threading .Lock ()
125-
128+
126129 def worker (value : int ) -> None :
127130 time .sleep (value / self .speed_factor )
128131 with lock :
129132 result .append (value )
130-
131- threads = []
133+
134+ threads : List [ threading . Thread ] = []
132135 for value in arr :
133136 if value < 0 :
134137 raise ValueError ("Sleep sort only works with non-negative integers" )
135138 thread = threading .Thread (target = worker , args = (value ,))
136139 threads .append (thread )
137140 thread .start ()
138-
141+
139142 for thread in threads :
140143 thread .join ()
141-
144+
142145 return result
143146
144147
145- if __name__ == "_main_" :
148+ if _name_ == "_main_" :
146149 # Example usage and test cases
147150 import doctest
148-
151+
149152 # Run doctests (using simple version for reliability)
150153 doctest .testmod ()
151-
154+
152155 print ("=== Sleep Sort Demo ===" )
153-
156+
154157 # Test with simple version (more reliable)
155158 test_arr = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ]
156159 print (f"Original array: { test_arr } " )
157-
160+
158161 simple_sorted = sleep_sort_simple (test_arr )
159162 print (f"Simple sorted: { simple_sorted } " )
160-
163+
161164 # Test with threaded version (may have timing issues in doctests)
162165 try :
163166 threaded_sorted = sleep_sort (test_arr )
164167 print (f"Threaded sorted: { threaded_sorted } " )
165168 except Exception as e :
166169 print (f"Threaded version error: { e } " )
167-
170+
168171 # Test with class-based version
169172 sorter = SleepSort (speed_factor = 20.0 )
170173 try :
171174 class_sorted = sorter .sort (test_arr )
172175 print (f"Class sorted: { class_sorted } " )
173176 except Exception as e :
174177 print (f"Class version error: { e } " )
175-
178+
176179 # Performance comparison
177180 print ("\n === Performance Test ===" )
178181 small_arr = [5 , 2 , 8 , 1 , 9 ]
179-
182+
180183 import time as time_module
181-
184+
182185 start = time_module .time ()
183186 simple_result = sleep_sort_simple (small_arr )
184187 simple_time = time_module .time () - start
185188 print (f"Simple version: { simple_result } (Time: { simple_time :.4f} s)" )
186-
189+
187190 # Demonstrate the algorithm concept
188191 print ("\n === Algorithm Concept ===" )
189192 print ("1. Each number goes to sleep for n milliseconds" )
190193 print ("2. Smaller numbers wake up first and get added to result" )
191194 print ("3. Larger numbers wake up later and get added after" )
192195 print ("4. Final result is sorted in ascending order!" )
193-
194-
196+
0 commit comments