Ruby Program to Implement Merge Sort

Ruby Program to Implement Merge Sort

Sorting is a crucial part of programming because it helps organize data in a meaningful way. One of the most efficient and widely used sorting algorithms is Merge Sort. Unlike simpler algorithms like Bubble Sort or Insertion Sort, Merge Sort uses a “divide and conquer” strategy. This means it splits the array into smaller parts, sorts each part individually, and then merges them back together in order. Understanding Merge Sort gives beginners a strong foundation in how more advanced algorithms work and introduces them to recursion in a practical way.

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

Merge Sort is particularly useful for large datasets because it is faster and more efficient than simple sorting methods. Its performance remains consistent even when the array is very large, making it a popular choice in many programming scenarios. By learning Merge Sort in Ruby, beginners can see how recursion and array manipulation work together to solve complex problems step by step. In this article, we will explore multiple ways to implement Merge Sort, helping you grasp both the concept and its practical application.

Program 1: Merge Sort Using Recursion

This first program demonstrates the classic recursive approach to Merge Sort, which is the most common way to implement it.

# Program 1: Merge Sort using recursion
def merge_sort(array)

  return array if array.length <= 1

  mid = array.length / 2
  left = merge_sort(array[0...mid])
  right = merge_sort(array[mid..-1])

  merge(left, right)

end

def merge(left, right)

  result = []

  until left.empty? || right.empty?

    if left.first <= right.first
      result << left.shift
    else
      result << right.shift
    end

  end

  result + left + right

end

numbers = [38, 27, 43, 3, 9, 82, 10]

sorted_array = merge_sort(numbers)

puts "Sorted array: #{sorted_array}"

In this program, the array is continuously split into halves until each subarray has one element. Then, the merge function combines these subarrays in sorted order. Beginners will find this approach useful because it clearly demonstrates recursion and shows how smaller problems can be combined to solve a bigger one. It also teaches the idea of comparing and merging arrays step by step.

Program 2: Merge Sort with Descending Order

Merge Sort can be easily modified to sort in descending order. This example helps beginners understand how small changes in logic can affect the outcome.

# Program 2: Merge Sort in descending order
def merge_sort_desc(array)

  return array if array.length <= 1

  mid = array.length / 2
  left = merge_sort_desc(array[0...mid])
  right = merge_sort_desc(array[mid..-1])

  merge_desc(left, right)

end

def merge_desc(left, right)

  result = []

  until left.empty? || right.empty?

    if left.first >= right.first
      result << left.shift
    else
      result << right.shift
    end

  end

  result + left + right

end

numbers = [20, 5, 15, 10, 30]

sorted_array = merge_sort_desc(numbers)

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

Here, the comparison in the merge function is reversed, so larger elements are placed first. This demonstrates to beginners that sorting logic can be adjusted for different needs and that the core algorithm remains the same while producing different results.

Program 3: Merge Sort Using Iterative Approach

Although Merge Sort is commonly implemented recursively, it can also be implemented iteratively. This program shows how to use loops instead of recursion.

# Program 3: Iterative Merge Sort
def merge_sort_iterative(array)

  width = 1

  while width < array.length

    i = 0

    while i < array.length

      left = array[i, width]
      right = array[i + width, width] || []
      array[i, left.length + right.length] = merge(left, right)
      i += 2 * width

    end

    width *= 2

  end

  array

end

def merge(left, right)

  result = []

  until left.empty? || right.empty?

    if left.first <= right.first
      result << left.shift
    else
      result << right.shift
    end

  end

  result + left + right

end

numbers = [12, 11, 13, 5, 6, 7]

sorted_array = merge_sort_iterative(numbers)

puts "Sorted array: #{sorted_array}"

In this iterative version, the array is merged in small sections repeatedly, doubling the size of merged subarrays in each pass. This helps beginners see how recursion can be replaced by loops while keeping the same sorting logic. It also introduces the concept of bottom-up processing in algorithms.

Program 4: Merge Sort with Strings

Merge Sort is not limited to numbers; it can also sort strings alphabetically. This program demonstrates sorting an array of strings.

# Program 4: Merge Sort with strings
def merge_sort(array)

  return array if array.length <= 1

  mid = array.length / 2

  left = merge_sort(array[0...mid])
  right = merge_sort(array[mid..-1])

  merge(left, right)

end

def merge(left, right)

  result = []

  until left.empty? || right.empty?

    if left.first <= right.first
      result << left.shift
    else
      result << right.shift
    end

  end

  result + left + right

end

words = ["banana", "apple", "orange", "grape", "kiwi"]

sorted_words = merge_sort(words)

puts "Sorted words: #{sorted_words}"

This example is particularly useful for beginners who want to sort text data. By comparing strings alphabetically, Merge Sort demonstrates that the algorithm can handle a wide range of data types, not just numbers. It also reinforces the merging concept in a real-world scenario.

Frequently Asked Questions (FAQ)

Merge Sort often raises questions among beginners. Here are some of the most common:

Q1: What is the time complexity of Merge Sort?
Merge Sort has a time complexity of O(n log n) for all cases, making it more efficient than simple sorting algorithms like Bubble Sort or Insertion Sort.

Q2: Is Merge Sort stable?
Yes, Merge Sort is a stable sorting algorithm, meaning it preserves the relative order of equal elements.

Q3: Can Merge Sort be used for large datasets?
Absolutely. Merge Sort is efficient and handles large datasets well because its time complexity remains consistent, regardless of the data size.

Q4: What are the benefits of Merge Sort over simpler algorithms?
Merge Sort is faster for large arrays, stable, and predictable. Its divide-and-conquer approach teaches important programming concepts like recursion and problem decomposition.

Conclusion

In this article, we explored how to implement Merge Sort in Ruby using recursion, iterative approaches, descending order, and even for strings. Merge Sort is a powerful and efficient sorting algorithm that helps beginners understand recursion, array manipulation, and the divide-and-conquer strategy. By practicing these examples, you will gain a solid understanding of sorting logic and develop confidence to tackle more complex algorithms. Merge Sort is not only practical but also a great learning tool, and experimenting with it in Ruby will make you more comfortable with programming concepts that are widely used in real-world applications.

Scroll to Top