|
1 | 1 | """ |
2 | | -Stalin Sort algorithm: Removes elements that are out of order. |
3 | | -Elements that are not greater than or equal to the previous element are discarded. |
4 | | -Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 |
| 2 | +A pure Python implementation of the Stalin sort algorithm. |
| 3 | +
|
| 4 | +For doctests run the following command: |
| 5 | + python3 -m doctest -v stalin_sort.py |
| 6 | +
|
| 7 | +For manual testing run: |
| 8 | + python3 stalin_sort.py |
5 | 9 | """ |
6 | 10 |
|
| 11 | +from typing import Any, Protocol |
7 | 12 |
|
8 | | -def stalin_sort(sequence: list[int]) -> list[int]: |
9 | | - """ |
10 | | - Sorts a list using the Stalin sort algorithm. |
11 | 13 |
|
| 14 | +class Comparable(Protocol): |
| 15 | + def __ge__(self, other: Any, /) -> bool: ... |
| 16 | + |
| 17 | + |
| 18 | +def stalin_sort[T: Comparable](sequence: list[T]) -> list[T]: |
| 19 | + """Sort a list of mutually comparable items using the Stalin sort algorithm. |
| 20 | +
|
| 21 | + Iterates through the sequence and retains elements that are greater than |
| 22 | + or equal to the last retained element, discarding any out-of-order items. |
| 23 | +
|
| 24 | + Reference: https://medium.com/@kaweendra/the-ultimate-sorting-algorithm-6513d6968420 |
| 25 | +
|
| 26 | + Complexity Analysis: |
| 27 | + - Time Complexity: O(n) where n is the number of elements in the list. |
| 28 | + - Space Complexity: O(n) auxiliary space for the output list. |
| 29 | +
|
| 30 | + Examples: |
12 | 31 | >>> stalin_sort([4, 3, 5, 2, 1, 7]) |
13 | 32 | [4, 5, 7] |
14 | | -
|
15 | 33 | >>> stalin_sort([1, 2, 3, 4]) |
16 | 34 | [1, 2, 3, 4] |
17 | | -
|
18 | 35 | >>> stalin_sort([4, 5, 5, 2, 3]) |
19 | 36 | [4, 5, 5] |
20 | | -
|
21 | 37 | >>> stalin_sort([6, 11, 12, 4, 1, 5]) |
22 | 38 | [6, 11, 12] |
23 | | -
|
24 | 39 | >>> stalin_sort([5, 0, 4, 3]) |
25 | 40 | [5] |
26 | | -
|
27 | 41 | >>> stalin_sort([5, 4, 3, 2, 1]) |
28 | 42 | [5] |
29 | | -
|
30 | 43 | >>> stalin_sort([1, 2, 3, 4, 5]) |
31 | 44 | [1, 2, 3, 4, 5] |
32 | | -
|
33 | 45 | >>> stalin_sort([1, 2, 8, 7, 6]) |
34 | 46 | [1, 2, 8] |
35 | | -
|
36 | 47 | >>> stalin_sort([]) |
37 | 48 | [] |
38 | | -
|
39 | 49 | >>> stalin_sort([7]) |
40 | 50 | [7] |
| 51 | + >>> stalin_sort([2.5, -1.0, 0.0, 3.2]) |
| 52 | + [2.5, 3.2] |
| 53 | + >>> stalin_sort(["d", "a", "e", "c", "f"]) |
| 54 | + ['d', 'e', 'f'] |
| 55 | + >>> stalin_sort([1, "a"]) |
| 56 | + Traceback (most recent call last): |
| 57 | + ... |
| 58 | + TypeError: '>=' not supported between instances of 'str' and 'int' |
41 | 59 | """ |
42 | 60 | if not sequence: |
43 | 61 | return [] |
|
0 commit comments