Ruby Program to Implement Bubble Sort

Ruby Program to Implement Bubble Sort

Sorting is one of the most common tasks in programming. Whether you are managing a list of names, numbers, or any kind of data, arranging it in order makes it easier to read and use. One of the simplest sorting algorithms to learn is Bubble Sort. It is called “Bubble Sort” because smaller elements “bubble” to the top of the list while larger elements sink to the bottom with each pass. Although it’s not the fastest sorting method for large datasets, it’s perfect for beginners to understand how sorting works step by step.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

In this article, we will explore how to implement Bubble Sort in Ruby, one of the most elegant and beginner-friendly programming languages. Ruby’s clear syntax makes it easy to write and understand sorting programs. By the end of this tutorial, you’ll not only know how to write a Bubble Sort program but also understand different ways to implement it, including loops and recursion. This will give you a solid foundation to explore more advanced algorithms in the future.

Program 1: Bubble Sort Using a Simple Loop

This first program demonstrates Bubble Sort using a simple loop approach. We will use a predefined array of numbers and sort them in ascending order.

# Program 1: Bubble Sort using simple loops
numbers = [64, 34, 25, 12, 22, 11, 90]

n = numbers.length

for i in 0...n

  for j in 0...(n - i - 1)

    if numbers[j] > numbers[j + 1]

      numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]

    end

  end

end

puts "Sorted array: #{numbers}"

This program works by comparing each pair of adjacent elements and swapping them if they are in the wrong order. The outer loop ensures we go through the array multiple times, while the inner loop handles the comparisons and swaps. Beginners will find this approach easy to follow because it directly reflects the Bubble Sort logic and visually shows how elements move toward their correct positions.

Program 2: Optimized Bubble Sort

This version of Bubble Sort includes an optimization that detects if no swaps were made during a pass. If the array is already sorted, the algorithm stops early, saving unnecessary passes.

# Program 2: Optimized Bubble Sort
numbers = [20, 18, 12, 8, 5, 15, 10]
n = numbers.length

for i in 0...n

  swapped = false

  for j in 0...(n - i - 1)

    if numbers[j] > numbers[j + 1]

      numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]
      swapped = true

    end

  end

  break unless swapped

end

puts "Sorted array: #{numbers}"

In this program, a swapped flag is used to check if any elements were exchanged in the current pass. If no swaps occur, the array is already sorted, and the outer loop breaks early. This makes the algorithm faster in the best-case scenario, especially for arrays that are almost sorted. For beginners, this example teaches how small optimizations can improve the efficiency of an algorithm without changing its core logic.

Program 3: Bubble Sort with a While Loop

In this version, we use a while loop instead of for loops. This approach introduces beginners to another way of controlling loops in Ruby.

# Program 3: Bubble Sort using a while loop
numbers = [29, 10, 14, 37, 13]
n = numbers.length
swapped = true

while swapped

  swapped = false
  i = 0

  while i < n - 1

    if numbers[i] > numbers[i + 1]

      numbers[i], numbers[i + 1] = numbers[i + 1], numbers[i]
      swapped = true

    end

    i += 1

  end

end

puts "Sorted array: #{numbers}"

Here, we keep iterating over the array as long as swaps are happening. This is efficient because it stops early if the array becomes sorted before completing all passes. Beginners will appreciate this approach because it introduces the idea of loop control with a condition that depends on the state of the array, showing how programs can be more dynamic.

Program 4: Bubble Sort Using Recursion

Recursion is a powerful concept where a function calls itself to solve smaller parts of a problem. Bubble Sort can also be implemented using recursion.

# Program 4: Bubble Sort using recursion
def bubble_sort_recursive(array, n = nil)

  n ||= array.length

  return array if n == 1

  for i in 0...(n - 1)

    if array[i] > array[i + 1]
      array[i], array[i + 1] = array[i + 1], array[i]
    end

  end

  bubble_sort_recursive(array, n - 1)

end

numbers = [5, 3, 8, 4, 2]

sorted_array = bubble_sort_recursive(numbers)

puts "Sorted array: #{sorted_array}"

In this program, the array is gradually reduced with each recursive call. The largest element “bubbles” to the end, and the function is called again on the remaining part of the array. This approach is useful for beginners to understand how recursion works and how problems can be broken into smaller parts.

Program 5: Bubble Sort in Descending Order

Most Bubble Sort examples focus on ascending order, but it can easily sort in descending order. This program helps beginners see the flexibility of the algorithm.

# Program 5: Bubble Sort in descending order
numbers = [3, 6, 1, 9, 2]
n = numbers.length

for i in 0...n

  for j in 0...(n - i - 1)

    if numbers[j] < numbers[j + 1]

      numbers[j], numbers[j + 1] = numbers[j + 1], numbers[j]

    end

  end

end

puts "Sorted array (descending): #{numbers}"

Here, we simply reverse the comparison condition to sort the array from largest to smallest. This example teaches beginners that small changes in logic can lead to different outcomes. Understanding this helps build confidence to modify algorithms for various needs.

Frequently Asked Questions (FAQ)

Bubble Sort can raise a few questions, especially for beginners. Here are some common queries:

Q1: What is the time complexity of Bubble Sort?
Bubble Sort has a worst-case and average-case time complexity of O(n²), which means it is not very efficient for large datasets. Its best-case complexity is O(n) when the array is already sorted, especially with optimized versions.

Q2: Is Bubble Sort better than other sorting algorithms?
For very small datasets, Bubble Sort works fine. However, for larger arrays, algorithms like Quick Sort or Merge Sort are faster and more efficient.

Q3: Can Bubble Sort be used on strings?
Yes, Bubble Sort can sort strings alphabetically. Instead of comparing numbers, it compares characters or strings using Ruby’s standard comparison operators.

Q4: Why is it called Bubble Sort?
It’s called Bubble Sort because smaller elements “bubble” to the top of the list while larger elements sink to the bottom with each pass, similar to bubbles rising in water.

Conclusion

In this article, we explored how to implement Bubble Sort in Ruby using multiple approaches, including simple loops, while loops, recursion, and descending order sorting. Bubble Sort is an excellent starting point for beginners to understand sorting and algorithm logic. By practicing these examples, you’ll not only strengthen your Ruby skills but also build a foundation for more advanced algorithms. Keep experimenting with arrays of different sizes and types, and soon you’ll feel confident tackling more complex programming challenges. Sorting has never been this friendly and approachable, and your journey into Ruby programming is just getting started.

Scroll to Top