Skip to content

Commit bc8e8f0

Browse files
authored
Added strand sort (TheAlgorithms#1982)
* Added strand sort * Review changes * Remove boilerplate code * Fixed flake error: E252 * Added missing return type hint
1 parent 565060a commit bc8e8f0

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

sorts/strand_sort.py

+51
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import operator
2+
3+
4+
def strand_sort(arr: list, reverse: bool = False, solution: list = 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__":
50+
assert strand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
51+
assert strand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]

0 commit comments

Comments
 (0)