Bubble Sort Visualization in Ruby2D

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.


1. Prerequisites

You will need:

Install Ruby2D

Install the Ruby2D gem:

gem install ruby2d

Verify the installation:

ruby -e "require 'ruby2d'; puts 'Ruby2D works!'"

2. Understanding the Visualization

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.


3. Creating the Window

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.


4. Configuration Values

Define constants to control the visualization:

ARRAY_SIZE = 60
BAR_WIDTH  = Window.width / ARRAY_SIZE
MAX_HEIGHT = Window.height - 20
SPEED      = 0.02

5. Generating the Data

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.


6. Drawing the Bars

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.


7. Bubble Sort State Variables

We need to track where we are in the algorithm:

i = 0
j = 0
sorting = true
last_step = Time.now

8. Animating with the Update Loop

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
Key idea: We perform only one comparison per frame, which allows us to see the algorithm step by step.

9. Starting the Program

Finally, start the Ruby2D event loop:

show

Run the script with:

ruby bubble_sort.rb

10. What to Try Next

Next Ruby2d tutorial:

Animated plasma effect