From bc8e8f03fda33788f77e85fa9fafe6e74ee30703 Mon Sep 17 00:00:00 2001 From: mateuszz0000 Date: Sun, 17 May 2020 22:48:39 +0200 Subject: [PATCH] Added strand sort (#1982) * Added strand sort * Review changes * Remove boilerplate code * Fixed flake error: E252 * Added missing return type hint --- sorts/strand_sort.py | 51 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 sorts/strand_sort.py diff --git a/sorts/strand_sort.py b/sorts/strand_sort.py new file mode 100644 index 000000000..a89135a06 --- /dev/null +++ b/sorts/strand_sort.py @@ -0,0 +1,51 @@ +import operator + + +def strand_sort(arr: list, reverse: bool = False, solution: list = None) -> list: + """ + 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] + + >>> strand_sort([4, 2, 5, 3, 0, 1], reverse=True) + [5, 4, 3, 2, 1, 0] + """ + _operator = operator.lt if reverse else operator.gt + solution = solution or [] + + if not arr: + return solution + + sublist = [arr.pop(0)] + for i, item in enumerate(arr): + if _operator(item, sublist[-1]): + sublist.append(item) + arr.pop(i) + + # merging sublist into solution list + if not solution: + solution.extend(sublist) + else: + while sublist: + item = sublist.pop(0) + for i, xx in enumerate(solution): + if not _operator(item, xx): + solution.insert(i, item) + break + else: + solution.append(item) + + strand_sort(arr, reverse, solution) + return solution + + +if __name__ == "__main__": + assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5] + assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]