|
| 1 | +""" |
| 2 | +Slowsort is a sorting algorithm. It is of humorous nature and not useful. |
| 3 | +It's based on the principle of multiply and surrender, |
| 4 | +a tongue-in-cheek joke of divide and conquer. |
| 5 | +It was published in 1986 by Andrei Broder and Jorge Stolfi |
| 6 | +in their paper Pessimal Algorithms and Simplexity Analysis |
| 7 | +(a parody of optimal algorithms and complexity analysis). |
| 8 | +
|
| 9 | +Source: https://en.wikipedia.org/wiki/Slowsort |
| 10 | +""" |
| 11 | + |
| 12 | +from typing import Optional |
| 13 | + |
| 14 | + |
| 15 | +def slowsort( |
| 16 | + sequence: list, start: Optional[int] = None, end: Optional[int] = None |
| 17 | +) -> None: |
| 18 | + """ |
| 19 | + Sorts sequence[start..end] (both inclusive) in-place. |
| 20 | + start defaults to 0 if not given. |
| 21 | + end defaults to len(sequence) - 1 if not given. |
| 22 | + It returns None. |
| 23 | + >>> seq = [1, 6, 2, 5, 3, 4, 4, 5]; slowsort(seq); seq |
| 24 | + [1, 2, 3, 4, 4, 5, 5, 6] |
| 25 | + >>> seq = []; slowsort(seq); seq |
| 26 | + [] |
| 27 | + >>> seq = [2]; slowsort(seq); seq |
| 28 | + [2] |
| 29 | + >>> seq = [1, 2, 3, 4]; slowsort(seq); seq |
| 30 | + [1, 2, 3, 4] |
| 31 | + >>> seq = [4, 3, 2, 1]; slowsort(seq); seq |
| 32 | + [1, 2, 3, 4] |
| 33 | + >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, 2, 7); seq |
| 34 | + [9, 8, 2, 3, 4, 5, 6, 7, 1, 0] |
| 35 | + >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, end = 4); seq |
| 36 | + [5, 6, 7, 8, 9, 4, 3, 2, 1, 0] |
| 37 | + >>> seq = [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]; slowsort(seq, start = 5); seq |
| 38 | + [9, 8, 7, 6, 5, 0, 1, 2, 3, 4] |
| 39 | + """ |
| 40 | + if start is None: |
| 41 | + start = 0 |
| 42 | + |
| 43 | + if end is None: |
| 44 | + end = len(sequence) - 1 |
| 45 | + |
| 46 | + if start >= end: |
| 47 | + return |
| 48 | + |
| 49 | + mid = (start + end) // 2 |
| 50 | + |
| 51 | + slowsort(sequence, start, mid) |
| 52 | + slowsort(sequence, mid + 1, end) |
| 53 | + |
| 54 | + if sequence[end] < sequence[mid]: |
| 55 | + sequence[end], sequence[mid] = sequence[mid], sequence[end] |
| 56 | + |
| 57 | + slowsort(sequence, start, end - 1) |
| 58 | + |
| 59 | + |
| 60 | +if __name__ == "__main__": |
| 61 | + from doctest import testmod |
| 62 | + |
| 63 | + testmod() |
0 commit comments