Skip to content

Commit 0d61dea

Browse files
authored
Create stalin_sort.py
1 parent e9e7c96 commit 0d61dea

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

sorts/stalin_sort.py

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
def stalin_sort(sequence: list[int]) -> list[int]:
2+
"""
3+
Stalin Sort algorithm: Removes elements that are out of order.
4+
Elements that are not greater than or equal to the previous element are discarded.
5+
Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420
6+
"""
7+
"""
8+
Sorts a list using the Stalin sort algorithm.
9+
10+
>>> stalin_sort([4, 3, 5, 2, 1, 7])
11+
[4, 5, 7]
12+
13+
>>> stalin_sort([1, 2, 3, 4])
14+
[1, 2, 3, 4]
15+
16+
>>> stalin_sort([4, 5, 5, 2, 3])
17+
[4, 5, 5]
18+
19+
>>> stalin_sort([6, 11, 12, 4, 1, 5])
20+
[6, 11, 12]
21+
22+
>>> stalin_sort([5, 0, 4, 3])
23+
[5]
24+
25+
>>> stalin_sort([5, 4, 3, 2, 1])
26+
[5]
27+
28+
>>> stalin_sort([1, 2, 3, 4, 5])
29+
[1, 2, 3, 4, 5]
30+
31+
>>> stalin_sort([1, 2, 8, 7, 6])
32+
[1, 2, 8]
33+
"""
34+
if any(x < 0 for x in sequence):
35+
raise ValueError("Sequence must only contain non-negative integers")
36+
37+
result = [sequence[0]]
38+
for i in range(1, len(sequence)):
39+
if sequence[i] >= result[-1]:
40+
result.append(sequence[i])
41+
42+
return result
43+
44+
45+
if __name__ == "__main__":
46+
import doctest
47+
doctest.testmod()

0 commit comments

Comments
 (0)