This tutorial walks you through creating an animated Bubble Sort visualization using Ruby and the Ruby2D graphics library. By the end, you will have a window that displays bars being compared and swapped in real time.
You will need:
Install the Ruby2D gem:
gem install ruby2d
Verify the installation:
ruby -e "require 'ruby2d'; puts 'Ruby2D works!'"
We will represent each number in the array as a vertical bar:
Bubble Sort works by repeatedly stepping through the list, comparing adjacent elements, and swapping them if they are out of order.
Start by requiring Ruby2D and creating a window:
require 'ruby2d'
set title: "Bubble Sort Visualization",
width: 800,
height: 400,
background: 'black'
This creates an 800×400 window with a black background.
Define constants to control the visualization:
ARRAY_SIZE = 60
BAR_WIDTH = Window.width / ARRAY_SIZE
MAX_HEIGHT = Window.height - 20
SPEED = 0.02
ARRAY_SIZE – number of barsBAR_WIDTH – width of each barMAX_HEIGHT – tallest possible barSPEED – delay between steps (smaller = faster)Create an array of random values:
array = Array.new(ARRAY_SIZE) { rand(20..MAX_HEIGHT) }
Each number will later become a bar on the screen.
Now create rectangles for each value in the array:
bars = array.each_with_index.map do |value, i|
Rectangle.new(
x: i * BAR_WIDTH,
y: Window.height - value,
width: BAR_WIDTH - 2,
height: value,
color: 'white'
)
end
Bars grow upward from the bottom of the window,
which is why we subtract the height from Window.height.
We need to track where we are in the algorithm:
i = 0
j = 0
sorting = true
last_step = Time.now
i – number of completed passesj – current comparison indexsorting – whether sorting is still runninglast_step – controls animation timing
Ruby2D calls the update block every frame.
We advance the algorithm slowly to create animation.
update do
next unless sorting
next if Time.now - last_step < SPEED
last_step = Time.now
bars.each { |b| b.color = 'white' }
if i < ARRAY_SIZE
if j < ARRAY_SIZE - i - 1
bars[j].color = 'red'
bars[j + 1].color = 'red'
if array[j] > array[j + 1]
array[j], array[j + 1] = array[j + 1], array[j]
bars[j].height, bars[j + 1].height =
bars[j + 1].height, bars[j].height
bars[j].y = Window.height - bars[j].height
bars[j + 1].y = Window.height - bars[j + 1].height
end
j += 1
else
j = 0
i += 1
end
else
sorting = false
bars.each { |b| b.color = 'green' }
end
end
Finally, start the Ruby2D event loop:
show
Run the script with:
ruby bubble_sort.rb