Skip to content

Commit 486fa37

Browse files
authored
Added Bead Sort Algorithm #920 (#2100)
1 parent 0b04e60 commit 486fa37

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

algorithms/sort/bead_sort.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""
2+
Bead Sort (also known as Gravity Sort) is a natural sorting algorithm that simulates how beads would settle under gravity on an abacus. It is most useful for sorting positive integers, especially when the range of numbers isn't excessively large. However, it is not a comparison-based sort and is generally impractical for large inputs due to its reliance on physical modeling.
3+
Time Complexity
4+
- Best Case: O(n) if the numbers are already sorted
5+
- Average Case: O(n^2) because each bead needs to be placed and then fall under gravity
6+
- Worst Case: O(n^2) since each bead must "fall" individually
7+
"""
8+
9+
def bead_sort(arr):
10+
if any(num < 0 for num in arr):
11+
raise ValueError("Bead sort only works with non-negative integers.")
12+
13+
max_num = max(arr) if arr else 0
14+
grid = [[0] * len(arr) for _ in range(max_num)]
15+
16+
# Drop beads (place beads in columns)
17+
for col, num in enumerate(arr):
18+
for row in range(num):
19+
grid[row][col] = 1
20+
21+
# Let the beads "fall" (count beads in each row)
22+
for row in grid:
23+
sum_beads = sum(row)
24+
for col in range(len(arr)):
25+
row[col] = 1 if col < sum_beads else 0
26+

0 commit comments

Comments
 (0)