Skip to content

Commit 0bcdd37

Browse files
committed
Add Sleep Sort algorithm with definition and Python implementation
1 parent 788d95b commit 0bcdd37

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

sorts/sleep_sort.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import threading
2+
import time
3+
4+
def sleep_sort(arr):
5+
"""
6+
Sorts a list of positive integers using Sleep Sort.
7+
8+
Args:
9+
arr (list[int]): List of positive integers to sort.
10+
11+
Returns:
12+
list[int]: Sorted list in ascending order.
13+
"""
14+
result = []
15+
16+
def sleeper(x):
17+
# Sleep for a duration proportional to the number
18+
time.sleep(x * 0.01) # scale down to avoid long delays
19+
result.append(x)
20+
21+
threads = [threading.Thread(target=sleeper, args=(num,)) for num in arr]
22+
23+
# Start all threads
24+
for t in threads:
25+
t.start()
26+
27+
# Wait for all threads to finish
28+
for t in threads:
29+
t.join()
30+
31+
return result
32+
33+
# Example Usage
34+
if __name__ == "__main__":
35+
numbers = [4, 1, 3, 2]
36+
sorted_numbers = sleep_sort(numbers)
37+
print("Original:", numbers)
38+
print("Sorted:", sorted_numbers)

0 commit comments

Comments
 (0)