Strand sort implementation source: https://en.wikipedia.org/wiki/Strand_sort :param arr: Unordered input list :param reverse: Descent ordering flag :param solution: Ordered items container Examples: >>> strand_sort([4, 2, 5, 3, 0, 1]) [0, 1, 2, 3, 4, 5] >>> st
(arr: list, reverse: bool = False, solution: list | None = None)
| 2 | |
| 3 | |
| 4 | def strand_sort(arr: list, reverse: bool = False, solution: list | None = None) -> list: |
| 5 | """ |
| 6 | Strand sort implementation |
| 7 | source: https://en.wikipedia.org/wiki/Strand_sort |
| 8 | |
| 9 | :param arr: Unordered input list |
| 10 | :param reverse: Descent ordering flag |
| 11 | :param solution: Ordered items container |
| 12 | |
| 13 | Examples: |
| 14 | >>> strand_sort([4, 2, 5, 3, 0, 1]) |
| 15 | [0, 1, 2, 3, 4, 5] |
| 16 | |
| 17 | >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) |
| 18 | [5, 4, 3, 2, 1, 0] |
| 19 | """ |
| 20 | _operator = operator.lt if reverse else operator.gt |
| 21 | solution = solution or [] |
| 22 | |
| 23 | if not arr: |
| 24 | return solution |
| 25 | |
| 26 | sublist = [arr.pop(0)] |
| 27 | for i, item in enumerate(arr): |
| 28 | if _operator(item, sublist[-1]): |
| 29 | sublist.append(item) |
| 30 | arr.pop(i) |
| 31 | |
| 32 | # merging sublist into solution list |
| 33 | if not solution: |
| 34 | solution.extend(sublist) |
| 35 | else: |
| 36 | while sublist: |
| 37 | item = sublist.pop(0) |
| 38 | for i, xx in enumerate(solution): |
| 39 | if not _operator(item, xx): |
| 40 | solution.insert(i, item) |
| 41 | break |
| 42 | else: |
| 43 | solution.append(item) |
| 44 | |
| 45 | strand_sort(arr, reverse, solution) |
| 46 | return solution |
| 47 | |
| 48 | |
| 49 | if __name__ == "__main__": |
no test coverage detected