- Notifications
You must be signed in to change notification settings - Fork 46.7k
/
Copy pathstrand_sort.py
51 lines (40 loc) · 1.35 KB
/
strand_sort.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
importoperator
defstrand_sort(arr: list, reverse: bool=False, solution: list|None=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.ltifreverseelseoperator.gt
solution=solutionor []
ifnotarr:
returnsolution
sublist= [arr.pop(0)]
fori, iteminenumerate(arr):
if_operator(item, sublist[-1]):
sublist.append(item)
arr.pop(i)
# merging sublist into solution list
ifnotsolution:
solution.extend(sublist)
else:
whilesublist:
item=sublist.pop(0)
fori, xxinenumerate(solution):
ifnot_operator(item, xx):
solution.insert(i, item)
break
else:
solution.append(item)
strand_sort(arr, reverse, solution)
returnsolution
if__name__=="__main__":
assertstrand_sort([4, 3, 5, 1, 2]) == [1, 2, 3, 4, 5]
assertstrand_sort([4, 3, 5, 1, 2], reverse=True) == [5, 4, 3, 2, 1]