11"""
22Sleep 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)
2020def sleep_sort (arr : List [int ]) -> List [int ]:
2121 """
2222 Sorts a list of non-negative integers using sleep sort algorithm.
23-
23+
2424 Args:
2525 arr (List[int]): List of non-negative integers to be sorted
26-
26+
2727 Returns:
2828 List[int]: Sorted list in ascending order
29-
29+
3030 Examples:
3131 >>> sleep_sort([3, 1, 2])
3232 [1, 2, 3]
33-
33+
3434 >>> sleep_sort([5, 2, 8, 1])
3535 [1, 2, 5, 8]
36-
36+
3737 >>> sleep_sort([1])
3838 [1]
39-
39+
4040 >>> sleep_sort([])
4141 []
4242 """
4343 if not arr :
4444 return []
45-
45+
4646 # Shared result list and lock for thread safety
4747 result = []
4848 lock = threading .Lock ()
49-
49+
5050 def worker (value : int ) -> None :
5151 """Worker function that sleeps for value seconds then appends to result."""
5252 time .sleep (value / 10 ) # Divide by 10 to make it faster for demonstration
5353 with lock :
5454 result .append (value )
55-
55+
5656 # Create and start threads
5757 threads = []
5858 for value in arr :
@@ -61,34 +61,34 @@ def worker(value: int) -> None:
6161 thread = threading .Thread (target = worker , args = (value ,))
6262 threads .append (thread )
6363 thread .start ()
64-
64+
6565 # Wait for all threads to complete
6666 for thread in threads :
6767 thread .join ()
68-
68+
6969 return result
7070
7171
7272def sleep_sort_simple (arr : List [int ]) -> List [int ]:
7373 """
7474 A simpler version of sleep sort without threads (sequential execution).
7575 This version is more reliable for testing.
76-
76+
7777 Args:
7878 arr (List[int]): List of non-negative integers to be sorted
79-
79+
8080 Returns:
8181 List[int]: Sorted list in ascending order
8282 """
8383 if not arr :
8484 return []
85-
85+
8686 # Create list of (value, index) pairs
8787 pairs = [(value , i ) for i , value in enumerate (arr )]
88-
88+
8989 # Sort based on value
9090 pairs .sort (key = lambda x : x [0 ])
91-
91+
9292 # Extract sorted values
9393 return [value for value , _ in pairs ]
9494
@@ -97,98 +97,96 @@ class SleepSort:
9797 """
9898 A class-based implementation of sleep sort with additional features.
9999 """
100-
100+
101101 def _init_ (self , speed_factor : float = 10.0 ):
102102 """
103103 Initialize SleepSort with a speed factor.
104-
104+
105105 Args:
106106 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:
115115 arr (List[int]): List of non-negative integers
116-
116+
117117 Returns:
118118 List[int]: Sorted list
119119 """
120120 if not arr :
121121 return []
122-
122+
123123 result = []
124124 lock = threading .Lock ()
125-
125+
126126 def worker (value : int ) -> None :
127127 time .sleep (value / self .speed_factor )
128128 with lock :
129129 result .append (value )
130-
130+
131131 threads = []
132132 for value in arr :
133133 if value < 0 :
134134 raise ValueError ("Sleep sort only works with non-negative integers" )
135135 thread = threading .Thread (target = worker , args = (value ,))
136136 threads .append (thread )
137137 thread .start ()
138-
138+
139139 for thread in threads :
140140 thread .join ()
141-
141+
142142 return result
143143
144144
145145if __name__ == "_main_" :
146146 # Example usage and test cases
147147 import doctest
148-
148+
149149 # Run doctests (using simple version for reliability)
150150 doctest .testmod ()
151-
151+
152152 print ("=== Sleep Sort Demo ===" )
153-
153+
154154 # Test with simple version (more reliable)
155155 test_arr = [3 , 1 , 4 , 1 , 5 , 9 , 2 , 6 ]
156156 print (f"Original array: { test_arr } " )
157-
157+
158158 simple_sorted = sleep_sort_simple (test_arr )
159159 print (f"Simple sorted: { simple_sorted } " )
160-
160+
161161 # Test with threaded version (may have timing issues in doctests)
162162 try :
163163 threaded_sorted = sleep_sort (test_arr )
164164 print (f"Threaded sorted: { threaded_sorted } " )
165165 except Exception as e :
166166 print (f"Threaded version error: { e } " )
167-
167+
168168 # Test with class-based version
169169 sorter = SleepSort (speed_factor = 20.0 )
170170 try :
171171 class_sorted = sorter .sort (test_arr )
172172 print (f"Class sorted: { class_sorted } " )
173173 except Exception as e :
174174 print (f"Class version error: { e } " )
175-
175+
176176 # Performance comparison
177177 print ("\n === Performance Test ===" )
178178 small_arr = [5 , 2 , 8 , 1 , 9 ]
179-
179+
180180 import time as time_module
181-
181+
182182 start = time_module .time ()
183183 simple_result = sleep_sort_simple (small_arr )
184184 simple_time = time_module .time () - start
185185 print (f"Simple version: { simple_result } (Time: { simple_time :.4f} s)" )
186-
186+
187187 # Demonstrate the algorithm concept
188188 print ("\n === Algorithm Concept ===" )
189189 print ("1. Each number goes to sleep for n milliseconds" )
190190 print ("2. Smaller numbers wake up first and get added to result" )
191191 print ("3. Larger numbers wake up later and get added after" )
192192 print ("4. Final result is sorted in ascending order!" )
193-
194-
0 commit comments