Skip to content

Commit a15f825

Browse files
l3str4ngecclauss
andauthored
Added bead sort (TheAlgorithms#2022)
* Added bead sort * Commit suggestion * Added checking before sort * Bead sort only works for sequences of nonegative integers Co-authored-by: Christian Clauss <cclauss@me.com>
1 parent 1f8a21d commit a15f825

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

sorts/bead_sort.py

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
"""
2+
Bead sort only works for sequences of nonegative integers.
3+
https://en.wikipedia.org/wiki/Bead_sort
4+
"""
5+
6+
7+
def bead_sort(sequence: list) -> list:
8+
"""
9+
>>> bead_sort([6, 11, 12, 4, 1, 5])
10+
[1, 4, 5, 6, 11, 12]
11+
12+
>>> bead_sort([9, 8, 7, 6, 5, 4 ,3, 2, 1])
13+
[1, 2, 3, 4, 5, 6, 7, 8, 9]
14+
15+
>>> bead_sort([5, 0, 4, 3])
16+
[0, 3, 4, 5]
17+
18+
>>> bead_sort([8, 2, 1])
19+
[1, 2, 8]
20+
21+
>>> bead_sort([1, .9, 0.0, 0, -1, -.9])
22+
Traceback (most recent call last):
23+
...
24+
TypeError: Sequence must be list of nonnegative integers
25+
26+
>>> bead_sort("Hello world")
27+
Traceback (most recent call last):
28+
...
29+
TypeError: Sequence must be list of nonnegative integers
30+
"""
31+
if any(not isinstance(x, int) or x < 0 for x in sequence):
32+
raise TypeError("Sequence must be list of nonnegative integers")
33+
for _ in range(len(sequence)):
34+
for i, (rod_upper, rod_lower) in enumerate(zip(sequence, sequence[1:])):
35+
if rod_upper > rod_lower:
36+
sequence[i] -= rod_upper - rod_lower
37+
sequence[i + 1] += rod_upper - rod_lower
38+
return sequence
39+
40+
41+
if __name__ == "__main__":
42+
assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5]
43+
assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]

0 commit comments

Comments
 (0)