Ruby Program for Bubble Sort with Example and Explanation
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
How to Think About It
Algorithm
Code
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]).inspectDry Run
Let's trace the array [3, 2, 1] through the bubble sort code.
Start with array
[3, 2, 1]
First pass comparisons and swaps
Compare 3 and 2, swap -> [2, 3, 1]; Compare 3 and 1, swap -> [2, 1, 3]
Second pass comparisons and swaps
Compare 2 and 1, swap -> [1, 2, 3]; Compare 2 and 3, no swap
Third pass no swaps
Compare 1 and 2, no swap; Compare 2 and 3, no swap; loop ends
Sorted array
[1, 2, 3]
| Pass | Array 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
arr = [5, 1, 4, 2, 8] puts arr.sort.inspect
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]).inspectComplexity: 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.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Bubble Sort | O(n^2) | O(1) | Learning sorting basics |
| Bubble Sort with Optimization | O(n^2) but faster in practice | O(1) | Slightly better bubble sort |
| Ruby Built-in Sort | O(n log n) | O(n) | Real-world sorting tasks |