Skip to content

Commit 8dc00d3

Browse files
ArvindAROOpoyeacclauss
authored andcommitted
Add sleep-sort (TheAlgorithms#1867)
* added sleepsort Adding sleepsort * Add doctest and typing for sleepsort * Use self-descriptive variable name * Update sleepsort.py * Update sorts/sleepsort.py Co-authored-by: John Law <[email protected]> Co-authored-by: Christian Clauss <[email protected]>
1 parent 5715faa commit 8dc00d3

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

sorts/sleepsort.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
"""Sleepsort is probably the wierdest of all sorting functions
2+
with time-complexity of O(max(input)+n) which is
3+
quite different from almost all other sorting techniques.
4+
If the number of inputs is small then the complexity
5+
can be approximated to be O(max(input)) which is a constant
6+
7+
If the number of inputs is large, the complexity is
8+
approximately O(n).
9+
10+
This function uses multithreading a kind of higher order programming
11+
and calls n functions, each with a sleep time equal to its number.
12+
Hence each of the functions wake in sorted form.
13+
14+
This function is not stable for very large values.
15+
16+
https://rosettacode.org/wiki/Sorting_algorithms/Sleep_sort
17+
"""
18+
19+
from time import sleep
20+
from threading import Timer
21+
from typing import List
22+
23+
24+
def sleepsort(values: List[int]) -> List[int]:
25+
"""
26+
Sort the list using sleepsort.
27+
>>> sleepsort([3, 2, 4, 7, 3, 6, 9, 1])
28+
[1, 2, 3, 3, 4, 6, 7, 9]
29+
>>> sleepsort([3, 2, 1, 9, 8, 4, 2])
30+
[1, 2, 2, 3, 4, 8, 9]
31+
"""
32+
sleepsort.result = []
33+
def append_to_result(x):
34+
sleepsort.result.append(x)
35+
mx = values[0]
36+
for v in values:
37+
if mx < v:
38+
mx = v
39+
Timer(v, append_to_result, [v]).start()
40+
sleep(mx+1)
41+
return sleepsort.result
42+
43+
if __name__ == '__main__':
44+
import doctest
45+
doctest.testmod()
46+
x = [3, 2, 4, 7, 3, 6, 9, 1]
47+
sorted_x = sleepsort(x)
48+
print(sorted_x)

0 commit comments

Comments
 (0)