Skip to content

Create stalin_sort.py #11988

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
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
47 changes: 47 additions & 0 deletions sorts/stalin_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
def stalin_sort(sequence: list[int]) -> list[int]:
"""

Check failure on line 2 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:2:1: SyntaxError: Expected an indented block after function definition

Check failure on line 2 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:2:1: SyntaxError: Expected an indented block after function definition
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
"""
"""

Check failure on line 7 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:7:1: SyntaxError: Unexpected indentation

Check failure on line 7 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:7:1: SyntaxError: Unexpected indentation
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]
"""
if any(x < 0 for x in sequence):
raise ValueError("Sequence must only contain non-negative integers")

result = [sequence[0]]
for i in range(1, len(sequence)):
if sequence[i] >= result[-1]:
result.append(sequence[i])

return result


if __name__ == "__main__":

Check failure on line 45 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:45:1: SyntaxError: Expected a statement

Check failure on line 45 in sorts/stalin_sort.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff

sorts/stalin_sort.py:45:1: SyntaxError: Expected a statement
import doctest
doctest.testmod()
Loading