Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Create stalin_sort.py (TheAlgorithms#11989)
* Create stalin_sort.py

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Update stalin_sort.py

* updating DIRECTORY.md

* Update stalin_sort.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Maxim Smolskiy <mithridatus@mail.ru>
Co-authored-by: MaximSmolskiy <MaximSmolskiy@users.noreply.github.com>
  • Loading branch information
4 people authored Aug 30, 2025
commit 9d52683ecbca6b8dcfa90a2e286d39b66ce5ffef
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -1301,6 +1301,7 @@
* [Shell Sort](sorts/shell_sort.py)
* [Shrink Shell Sort](sorts/shrink_shell_sort.py)
* [Slowsort](sorts/slowsort.py)
* [Stalin Sort](sorts/stalin_sort.py)
* [Stooge Sort](sorts/stooge_sort.py)
* [Strand Sort](sorts/strand_sort.py)
* [Tim Sort](sorts/tim_sort.py)
Expand Down
47 changes: 47 additions & 0 deletions sorts/stalin_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
"""
Stalin Sort algorithm: Removes elements that are out of order.
Elements that are not greater than or equal to the previous element are discarded.
Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420
"""


def stalin_sort(sequence: list[int]) -> list[int]:
"""
Sorts a list using the Stalin sort algorithm.

>>> stalin_sort([4, 3, 5, 2, 1, 7])
[4, 5, 7]

>>> stalin_sort([1, 2, 3, 4])
[1, 2, 3, 4]

>>> stalin_sort([4, 5, 5, 2, 3])
[4, 5, 5]

>>> stalin_sort([6, 11, 12, 4, 1, 5])
[6, 11, 12]

>>> stalin_sort([5, 0, 4, 3])
[5]

>>> stalin_sort([5, 4, 3, 2, 1])
[5]

>>> stalin_sort([1, 2, 3, 4, 5])
[1, 2, 3, 4, 5]

>>> stalin_sort([1, 2, 8, 7, 6])
[1, 2, 8]
"""
result = [sequence[0]]
for element in sequence[1:]:
if element >= result[-1]:
result.append(element)

return result


if __name__ == "__main__":
import doctest

doctest.testmod()