This repository was archived by the owner on Sep 7, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathbead_sort.rb
More file actions
78 lines (67 loc) · 1.51 KB
/
bead_sort.rb
File metadata and controls
78 lines (67 loc) · 1.51 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# A Ruby implementation of the Bead Sort algorithm
#
# "I" represents empty space in the bead grid
# "O" represents a bead in the bead grid
require "pp"
def bead_sort(unsorted_array)
# Display unsorted array
puts "Unsorted array"
pp unsorted_array
puts "\n"
# Fill bead grid with values
bead_grid = Array.new(unsorted_array.length) { Array.new(unsorted_array.max, "I") }
unsorted_array.each_with_index do |value, index|
while value > 0
value = value - 1
bead_grid[index][value] = "O"
end
end
# Display initial bead grid
puts "Initial bead grid"
pp bead_grid
puts "\n"
# Let "gravity" sort the bead grid
bead_grid = bead_grid.transpose
bead_grid.each do |value|
value.sort!
end
bead_grid = bead_grid.transpose
# Display resulting bead grid
puts "Resulting bead grid"
pp bead_grid
puts "\n"
# Count beads to get sorted array
sorted_array = []
bead_grid.each do |value|
sorted_array.append(value.count("O"))
end
# Display sorted array
puts "Sorted array"
pp sorted_array
puts "\n"
# Return sorted array
sorted_array
end
# Testing the algorithm
array = [5, 2, 0, 1]
bead_sort(array)
# Output
#
# Unsorted array
# [5, 2, 0, 1]
#
# Initial bead grid
# [["O", "O", "O", "O", "O"],
# ["O", "O", "I", "I", "I"],
# ["I", "I", "I", "I", "I"],
# ["O", "I", "I", "I", "I"]]
#
# Resulting bead grid
# [["I", "I", "I", "I", "I"],
# ["O", "I", "I", "I", "I"],
# ["O", "O", "I", "I", "I"],
# ["O", "O", "O", "O", "O"]]
#
# Sorted array
# [0, 1, 2, 5]
#