Merge Sort in Ruby

Welcome to Merge Sort

Welcome, aspiring programmer! Today's topic is Merge Sort. Merge Sort is a sorting technique reminiscent of organizing a shuffled deck of cards in order. For large-scale data, Merge Sort can outperform typical techniques. Today, we'll explore Merge Sort, code it in Ruby, and analyze its efficiency. Ready? Let's get started!

What is Merge Sort?

In computer science, Merge Sort is a popular method to sort elements. Merge Sort uses the 'divide-and-conquer' strategy similar to the Quick Sort algorithm. The three main steps of Merge Sort are:

  1. Split the array into halves.
  2. Sort each half separately.
  3. Merge the sorted halves back together.

Understanding the Merge Process

We will begin by building code for merging two sorted parts. The merge process involves comparing elements from two halves and merging them so the resulting list is sorted.

Let's code a merge function in Ruby to achieve this. We will make use of Ruby's Array operations and slice capabilities.

Ruby
def merge(arr, left, mid, right)
  # Split the array into a left and a right part
  left_array = arr[left..mid]
  right_array = arr[mid+1..right]

  # Initialize indices for merging
  i, j, k = 0, 0, left

  # Merge left and right arrays
  while i < left_array.size && j < right_array.size
    # Compare and pick smaller element
    if left_array[i] <= right_array[j]
      arr[k] = left_array[i] # Copy from left part
      i += 1
    else
      arr[k] = right_array[j] # Copy from right part
      j += 1
    end
    k += 1 # Move to next index
  end

Here, we've divided our original list into two halves, left_array and right_array.

Merging the Halves Back Together

Now, we'll sort and merge these halves:

Ruby
  while i < left_array.size
    arr[k] = left_array[i]
    i += 1
    k += 1
  end

  while j < right_array.size
    arr[k] = right_array[j]
    j += 1
    k += 1
  end
end

This code places two pointers, i and j, at the beginning of the left_array and right_array. It selects the smaller element, places it in the final array arr, and moves the corresponding pointer onward. This continues until all elements are merged.

Once one of the pointers reaches the end of its array, some elements might be left in the other array. To handle this, let's copy the remaining elements of both arrays (if any) to the end of the resulting arr array.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal