0
0
RubyProgramBeginner · 2 min read

Ruby Program for Bubble Sort with Example and Explanation

A Ruby program for bubble sort swaps adjacent elements using nested loops until the array is sorted; for example, def bubble_sort(arr); n = arr.length; loop do; swapped = false; (n-1).times do |i|; if arr[i] > arr[i+1]; arr[i], arr[i+1] = arr[i+1], arr[i]; swapped = true; end; end; break unless swapped; end; arr; end sorts the array in place.
📋

Examples

Input[3, 2, 1]
Output[1, 2, 3]
Input[5, 1, 4, 2, 8]
Output[1, 2, 4, 5, 8]
Input[]
Output[]
🧠

How to Think About It

To sort an array using bubble sort, repeatedly compare each pair of adjacent elements and swap them if they are in the wrong order. Keep doing this until no swaps are needed, which means the array is sorted.
📐

Algorithm

1
Get the array to sort.
2
Repeat until no swaps happen:
3
Compare each pair of adjacent elements in the array.
4
Swap them if the first is greater than the second.
5
Return the sorted array.
💻

Code

ruby
def bubble_sort(arr)
  n = arr.length
  loop do
    swapped = false
    (n - 1).times do |i|
      if arr[i] > arr[i + 1]
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
        swapped = true
      end
    end
    break unless swapped
  end
  arr
end

puts bubble_sort([5, 1, 4, 2, 8]).inspect
Output
[1, 2, 4, 5, 8]
🔍

Dry Run

Let's trace the array [3, 2, 1] through the bubble sort code.

1

Start with array

[3, 2, 1]

2

First pass comparisons and swaps

Compare 3 and 2, swap -> [2, 3, 1]; Compare 3 and 1, swap -> [2, 1, 3]

3

Second pass comparisons and swaps

Compare 2 and 1, swap -> [1, 2, 3]; Compare 2 and 3, no swap

4

Third pass no swaps

Compare 1 and 2, no swap; Compare 2 and 3, no swap; loop ends

5

Sorted array

[1, 2, 3]

PassArray State
1[2, 3, 1] after first swap, then [2, 1, 3] after second swap
2[1, 2, 3] after swap, then no swap
3[1, 2, 3] no swaps, sorting done
💡

Why This Works

Step 1: Compare adjacent elements

The code uses a loop to check each pair of neighbors with arr[i] > arr[i + 1].

Step 2: Swap if out of order

If the left element is bigger, it swaps them using arr[i], arr[i + 1] = arr[i + 1], arr[i].

Step 3: Repeat until sorted

The outer loop continues until no swaps happen, meaning the array is sorted.

🔄

Alternative Approaches

Using Ruby's built-in sort method
ruby
arr = [5, 1, 4, 2, 8]
puts arr.sort.inspect
This is much faster and simpler but does not show the bubble sort algorithm.
Bubble sort with early exit optimization
ruby
def bubble_sort(arr)
  n = arr.length
  loop do
    swapped = false
    (n - 1).times do |i|
      if arr[i] > arr[i + 1]
        arr[i], arr[i + 1] = arr[i + 1], arr[i]
        swapped = true
      end
    end
    break unless swapped
    n -= 1
  end
  arr
end

puts bubble_sort([5, 1, 4, 2, 8]).inspect
This reduces the number of comparisons after each pass since the largest elements settle at the end.

Complexity: O(n^2) time, O(1) space

Time Complexity

Bubble sort uses nested loops, comparing pairs repeatedly, so it takes about n squared steps for n elements.

Space Complexity

It sorts the array in place, so it uses only a small fixed amount of extra memory.

Which Approach is Fastest?

Ruby's built-in sort is much faster (O(n log n)) than bubble sort, which is mainly for learning.

ApproachTimeSpaceBest For
Bubble SortO(n^2)O(1)Learning sorting basics
Bubble Sort with OptimizationO(n^2) but faster in practiceO(1)Slightly better bubble sort
Ruby Built-in SortO(n log n)O(n)Real-world sorting tasks
💡
Stop the sorting early if no swaps happen in a pass to save time.
⚠️
Forgetting to swap elements correctly or not checking all pairs causes incorrect sorting.